search
HomeWeb Front-endJS TutorialWhat new special effects have been added to vue-cli3.0?

This time I will bring you what new special effects vue-cli3.0 has added, and what are the precautions for the new special effects of vue-cli3.0. The following is a practical case, let’s take a look.

Vue-cli 3.0 has been used in recent development projects. The user experience can be said to be very good. The templates are more customized and the configuration is simpler. The following summarizes some experiences during the application process.

New project

# 安装
npm install -g @vue/cli
# 新建项目
vue create my-project
# 项目启动
npm run serve
# 打包
npm run build

The packaged file has preloading (preload/prefetch) injected into the reference resources, and the manifest/icon link is injected when the PWA plug-in is enabled, and Inlines webpack runtime/chunk manifest for best performance.

Function configuration

Function selection

## Version 3.0 includes default default configuration And user-defined configuration. After the user-defined configuration, you will be asked whether to save the current configuration function as the default value for future project configurations, so that it can be used directly next time without the need to configure again.

Custom function configuration includes the following functions:

  1. TypeScript

  2. ##Progressive Web App (PWA) Support
  3. Router
  4. ##Vuex
  5. ##CSS Pre-processors

  6. Linter / Formatter

  7. Unit Testing

  8. E2E Testing

  9. can be experienced according to the project size and functionality To configure different functions, use the space bar to select/invert selection, press the a key to select all/unselect all, press the i key to invert the selected items, and use the up and down keys to move the selection up and down.

Function detailed configuration

After selecting the function, you will be asked for more detailed configuration,

TypeScript:

Whether to use class-style component syntax: Use class-style component syntax?

  1. Whether to use babel for escaping: Use Babel alongside TypeScript for auto-detected polyfills?

  2. CSS Pre-processors:

Select CSS pre-processing type: Pick a CSS pre-processor

  1. Linter / Formatter

Select Linter / Formatter specification type: Pick a linter / formatter config

  1. Select lint mode, check when saving/check when submitting: Pick additional lint features

  2. Testing

Select Unit testing mode

  1. Select E2E testing method

  2. Select the storage location of custom configurations such as Babel, PostCSS, ESLint, etc. Where do you prefer placing config for Babel, PostCSS, ESLint, etc. ?

vue.config.js Custom configuration

vue.config.js Complete default configuration

module.exports = {
 // 基本路径
 baseUrl: '/',
 // 输出文件目录
 outputDir: 'dist',
 // eslint-loader 是否在保存的时候检查
 lintOnSave: true,
 // use the full build with in-browser compiler?
 // https://vuejs.org/v2/guide/installation.html#Runtime-Compiler-vs-Runtime-only
 compiler: false,
 // webpack配置
 // see https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md
 chainWebpack: () => {},
 configureWebpack: () => {},
 // vue-loader 配置项
 // https://vue-loader.vuejs.org/en/options.html
 vueLoader: {},
 // 生产环境是否生成 sourceMap 文件
 productionSourceMap: true,
 // css相关配置
 css: {
  // 是否使用css分离插件 ExtractTextPlugin
  extract: true,
  // 开启 CSS source maps?
  sourceMap: false,
  // css预设器配置项
  loaderOptions: {},
  // 启用 CSS modules for all css / pre-processor files.
  modules: false
 },
 // use thread-loader for babel & TS in production build
 // enabled by default if the machine has more than 1 cores
 parallel: require('os').cpus().length > 1,
 // 是否启用dll
 // See https://github.com/vuejs/vue-cli/blob/dev/docs/cli-service.md#dll-mode
 dll: false,
 // PWA 插件相关配置
 // see https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa
 pwa: {},
 // webpack-dev-server 相关配置
 devServer: {
  open: process.platform === 'darwin',
  host: '0.0.0.0',
  port: 8080,
  https: false,
  hotOnly: false,
  proxy: null, // 设置代理
  before: app => {}
 },
 // 第三方插件配置
 pluginOptions: {
  // ...
 }
}
Set proxy

# string
module.exports = {
 devServer: {
  proxy: '<url>'
 }
}
# Object
module.exports = {
 devServer: {
  proxy: {
   '/api': {
    target: '<url>',
    ws: true,
    changeOrigin: true
   },
   '/foo': {
    target: '<other_url>'
   }
  }
 }
}</other_url></url></url>

Enable dll

After enabling dll, the [chunkhash] value of the vendor generated by our dynamic library file will be the same every time it is packaged. The value can be true/false, or it can be specified. Specific code base.

module.exports = {
 dll: true
}
module.exports = {
 dll: [
  'dep-a',
  'dep-b/some/nested/file.js'
 ]
}

Static resource path

Relative path

The static resource path starting with @ represents /src

  1. The static resource path starts with ~, which can import resources in node modules

  2. Static resource references in the public folder

     # 在 public/index.html中引用静态资源
     
     <link>favicon.ico" rel="external nofollow" >
     # vue templates中,需要在data中定义baseUrl
     <template>
      <img  src="/static/imghwm/default1.png" data-src="`${baseUrl}my-image.png`" class="lazy" alt="What new special effects have been added to vue-cli3.0?" >
     </template>
     <script>
      data () {
       return {
        baseUrl: process.env.BASE_URL
       }
      }
     </script>
Webpack configuration modification

Use webpack-chain to modify webpack-related configurations. It is strongly recommended to be familiar with webpack-chain and vue-cli source code in order to better understand the configuration items of this option. Module processing configuration

// vue.config.js
module.exports = {
 chainWebpack: config => {
  config.module
   .rule('js')
    .include
     .add(/some-module-to-transpile/) // 要处理的模块
 }
}

Modify webpack Loader configuration

// vue.config.js
module.exports = {
 chainWebpack: config => {
  config.module
   .rule('scss')
   .use('sass-loader')
   .tap(options =>
    merge(options, {
     includePaths: [path.resolve(__dirname, 'node_modules')],
    })
   )
 }
}

Modify webpack Plugin configuration

// vue.config.js
module.exports = {
 chainWebpack: config => {
  config
   .plugin('html')
   .tap(args => {
    return [/* new args to pass to html-webpack-plugin's constructor */]
   })
 }
}

eg: 在本次项目较小,只对uglifyjs进行了少量的修改,后期如果还有配置上优化会继续添加。

chainWebpack: config => {
  if (process.env.NODE_ENV === 'production') { 
    config
      .plugin('uglify')
      .tap(([options]) =>{
        // 去除 console.log
        return [Object.assign(options, {
          uglifyOptions: { compress: {
            drop_console : true,
            pure_funcs: ['console.log']
          }}
        })]
      })
  }
}

全局变量的设置

在项目根目录创建以下项目:

.env        # 在所有环节中执行
.env.local     # 在所有环境中执行,git会ignored
.env.[mode]     # 只在特定环境执行( [mode] 可以是 "development", "production" or "test" )
.env.[mode].local  # 在特定环境执行, git会ignored
.env.development  # 只在生产环境执行
.env.production   # 只在开发环境执行

在文件里配置键值对:

# 键名须以VUE_APP开头
VUE_APP_SECRET=secret

在项目中访问:

console.log(process.env.VUE_APP_SECRET)

这样项目中的 process.env.VUE_APP_SECRET 就会被 secret 所替代。

vue-cli 3 就项目性能而言已经相当友好了,私有制定性也特别强,各种配置也特别贴心,可以根据项目大小和特性制定私有预设,对前期项目搭建而言效率极大提升了。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样对JS+TypeScript中class进行使用

vue计算属性与侦听器实战项目详解

The above is the detailed content of What new special effects have been added to vue-cli3.0?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools