search
HomeWeb Front-endJS TutorialDetailed explanation of vue-cli3.0 configuration

Detailed explanation of vue-cli3.0 configuration

Apr 27, 2018 pm 01:37 PM
Detailed explanationConfiguration

This time I will bring you a detailed explanation of vue-cli3.0 configuration. What are the precautions when using vue-cli3.0 configuration? The following is a practical case, let’s take a look.

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="Detailed explanation of vue-cli3.0 configuration" >
     </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: This project is small, only for uglifyjs has made a small amount of modifications, and will be added later if there are configuration optimizations.

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']
          }}
        })]
      })
  }
}

Setting of global variables

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

.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中文网其它相关文章!

推荐阅读:

Vue.js中router如何传递参数

Vue实现不刷新分页

The above is the detailed content of Detailed explanation of vue-cli3.0 configuration. 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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.