References
Si no: https://segmentfault.com/a/1190000019920162
Manual: https://cli.vuejs.org/zh/config/
vue.config.js global configuration
Configuration parameters:
1. Two configuration methods
module.exports = {
// 选项……
}
const {
defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
// 选项……
})
2.baseUrl / baseUrl
Static resource address.
module.exports = {
// baseURL:'./' // vue-cli版本是3.2.0以前的
publicPath:'./' // publicPath属性适用于vue-cli 高于3.2.0的项目
}
Switching modes of different development environments:
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? '/生产环境路径/' : '/'
}
3.outputDir
The directory address of the production build files .
module.exports = {
outputDir:'newBuild'
}
4.assetsDir
The directory (relative to outputDir) where the generated static resources (js, css, img, fonts) are placed.
module.exports = {
assetsDir:'staticDir'
}
5.indexPath
Specifies the output path (relative to outputDir) of the generated index.html.
module.exports = {
indexPath:'indexHtmlPath'
}
6.filenameHashing
Generated static resources include hashes in their filenames for better control of caching, turn off filename hashing by setting this option to false.
module.exports= {
filenameHashing:false,
}
7.pages
Multi-page packaging
module.exports = {
pages: {
index: {
// page 的入口
entry: 'src/index/main.js',
// 模板来源
template: 'public/index.html',
// 在 dist/index.html 的输出
filename: 'index.html',
chunks: ['chunk-vendors', 'chunk-common', 'index']
}
}
}
8.lintOnSave
Whether to lint code on every save via eslint-loader in development environment. This value will take effect after @vue/cli-plugin-eslint is installed.
module.exports= {
lintOnSave:false,
}
9.devServer
Make the browser overlay show both warnings and errors
module.exports = {
devServer: {
overlay: {
warnings: true,
errors: true
}
}
}
File initial value:
/**
* @type {import('@vue/cli-service').ProjectOptions}
*/
module.exports = {
// 选项...
}
Alternatively, you can also use the defineConfig
helper for better type hinting:
// vue.config.js
const {
defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
// 选项
})
10.runtimeCompiler
Whether to use a Vue build that includes the runtime compiler.
publicPath
The original baseUrl
, baseUrl has been deprecated since Vue CLI 3.3 and used insteadpublicPath
when deploying the application package 基本 URL
. The usage is the same as output.publicPath of webpack itself, but Vue CLI also needs this value in some other places, so always use publicPath instead of directly modifying output.publicPath of webpack.
By default, the Vue CLI will assume that your app is deployed on a domain name 根路径上
, such as https://www.my-app.com/. If the application is deployed on a subpath, you need to specify the subpath with this option. For example, if your app is deployed at https://www.my-app.com/my-app/, setpublicPath 为 /my-app/
This value can also be set 空字符串 ('') 或是相对路径 ('./')
so that all 资源都会被链接为相对路径
such typed packages can be deployed in arbitrary paths , and can also be used in filesystems like Cordova hybrid applications.
Restrictions on
Relative PublicPath There are some restrictions on the use of publicPath relative to the path. Relative publicPath should be avoided in the following cases:
- When using HTML5 history.pushState based routing;
- When building a multi-page app with the pages option.
This value also takes effect in the development environment. If you want to host the development server on the root path, you can use a conditional value:
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? '/production-sub-path/' : '/'
}
outputDir
The directory where the production build filesvue-cli-service build
are generated when running . (Pass in at build time to turn off this behavior).注意目标目录的内容在构建之前会被清除
--no-clean
Tip:
Always use outputDir instead of modifying webpack's output.path.
assetsDir
Directory to place the generated static resources (js, css, img, fonts).
indexPath
Specifies the output path (relative to outputDir) of the generated index.html. Can also be an absolute path
filenameHashing
Filename hash encryption settings.
Reference: https://blog.csdn.net/weixin_35773751/article/details/121726540
pages
Build the application in multi-page mode. Each "page" should have a corresponding JavaScript entry file. The value should be an object, the key of the object is the name of the entry, and the value is:
entry, template, filename, title 和 chunks
The specified object (all optional except entry)- a string specifying its entry
module.exports = {
pages: {
index: {
// page 的入口
entry: 'src/index/main.js',
// 模板来源
template: 'public/index.html',
// 在 dist/index.html 的输出
filename: 'index.html',
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: 'Index Page',
// 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ['chunk-vendors', 'chunk-common', 'index']
},
// 当使用只有入口的字符串格式时,
// 模板会被推导为 `public/subpage.html`
// 并且如果找不到的话,就回退到 `public/index.html`。
// 输出文件名会被推导为 `subpage.html`。
subpage: 'src/subpage/main.js'
}
}
lintOnSave
Lint the code every time you save through eslint-loader in the development environment
When set to true or warning, eslint-loader will output lint errors as compilation warnings. By default, warnings will only be output to the command line and will not fail compilation.
If you want lint errors to be displayed directly in the browser during development, you can use lintOnSave: 'default'. This forces eslint-loader to output lint errors as compilation errors, and also means that lint errors will cause compilation to fail.
Setting it to error will cause eslint-loader to output lint warnings as compilation errors, which means that lint warnings will cause compilation to fail.
Alternatively, you can set the browser overlay to display both warnings and errors:
// vue.config.js
module.exports = {
devServer: {
overlay: {
warnings: true,
errors: true
}
}
}
When lintOnSave is a truthy value, eslint-loader is enabled on both development and production builds. If you want to disable eslint-loader on production builds, you can use the following configuration:
// vue.config.js
module.exports = {
lintOnSave: process.env.NODE_ENV !== 'production'
}
runtimeCompiler
Comparison: the difference between runtimecompiler and runtimeonly in vue
If you still use template in future development, you need to choose runtimecompiler.
If you use .vue folder development in future development, you can choose runtimeonly
runtimecompiler
runtimeonly
transpileDependencies
By default babel-loader ignores all files in node_modules. You can enable this option to avoid untranspiled third-party dependencies in the built code.
However, transpiling all dependencies may slow down the build. If you are concerned about build performance, you can only translate some specific dependencies: pass an array to this option, listing the names of third-party packages or regular expressions that need to be translated.
productionSourceMap
The source map of the production environment is not required, it can be set to false to speed up the production environment build
crossorigin
integrity
configureWebpack
This value is an object that will be merged into the final configuration via webpack-merge.
If the value is a function, it will receive the parsed configuration as an argument. This function can either modify the configuration and return nothing, or it can return a cloned or merged version of the configuration.
chainWebpack
is a function that will receive a webpack-chain based ChainableConfig instance. Allows finer-grained modifications to the internal webpack configuration.
css.requireModuleExtension
By default, only files ending in *.module.[ext] are considered CSS Modules modules. When set to false you can remove the .module from the filename and treat all *.(css|scss|sass|less|styl(us)?) files as CSS Modules modules.
css.extract
Whether to extract CSS from the component into a separate CSS file (instead of inline code that is dynamically injected into JavaScript).
Also when building Web Components it is always disabled (styles are inline and injected into shadowRoot).
When building as a library, you can also set this to false to prevent users from importing CSS themselves.
Fetching CSS is disabled by default in development mode because it is not compatible with CSS hot reloading. However, you can still explicitly set this value to true to force fetching in all cases.
css.sourceMap
Whether to enable source maps for CSS. Setting to true may affect build performance.
css.loaderOptions
Pass options to CSS related loaders. E.g:
module.exports = {
css: {
loaderOptions: {
css: {
// 这里的选项会传递给 css-loader
},
postcss: {
// 这里的选项会传递给 postcss-loader
}
}
}
}
devServer
Some values like host, port and https may be overridden by command line arguments.
Some values like publicPath and historyApiFallback should not be modified because they need to be synchronized with the development server's publicPath to work properly.
devServer.proxy
If yours 前端应用
and 后端 API 服务器
are not running on the same host, you need to proxy API requests to the API server in the development environment. This problem can be configured via the devServer.proxy option in vue.config.js.
devServer.proxy can be a string pointing to the development environment API server:
module.exports = {
devServer: {
proxy: 'http://localhost:4000'
}
}
For more proxy control behavior, you can also use a path: options object
module.exports = {
devServer: {
proxy: {
'/api': {
target: '<url>',
ws: true,
changeOrigin: true
},
'/foo': {
target: '<other_url>'
}
}
}
}
pluginOptions
This is an object that does not do any schema validation, so it can be used to pass any 3rd party plugin options. E.g:
module.exports = {
pluginOptions: {
foo: {
// 插件可以作为 `options.pluginOptions.foo` 访问这些选项。
}
}
}
Babel
Babel can be configured via babel.config.js.
ESLint
ESLint can be configured via the eslintConfig field in .eslintrc or package.json.
TypeScript
TypeScript can be configured via tsconfig.json.
2. Example demonstration
view.config.js
(The basic explanation is in the comments, and the detailed explanation is under the example)
module.exports = {
lintOnSave: true, // ------------------------ 设置在开发环境下每次保存代码都启用eslint验证
productionSourceMap: false, // -------------- 设置生产环境的 source map 开启与关闭
css: {
// ----------------------------------- 全局引入公共样式文件
loaderOptions: {
sass: {
data: `@import "@src/css/base.scss";`
}
}
}
chainWebpack: (config) => {
// -------------- webpack 配置
config.externals({
// --------------------- 忽略打包的文件
'vue': 'Vue',
'vue-router': 'VueRouter',
'vuex': 'Vuex',
'axios': 'axios',
'element-ui': 'ELEMENT',
})
const entry = config.entry('app') // ------ 入口起点
entry
.add('babel-polyfill') // --------------- 添加插件,用于实现浏览器不支持原生功能的代码,例如对于一些不支持ES6的浏览器
.end()
entry
.add('classlist-polyfill') // ----------- 解决部分浏览器不支持一些方法,添加以后达到能支持的效果,例如element.classlist.add()方法在ie9中是不支持
.end()
entry
.add('@/mock') // ----------------------- 添加mock
.end()
},
devServer: {
// ----------------------------- 代理
// 端口配置
port: 1888,
// 反向代理配置
proxy: {
'/api': {
target: 'https://saber.bladex.vip',
ws: true, // ------------------------- 代理 websockets
pathRewrite: {
// ------------------- 重写
'^/api': '/'
}
}
}
}
}
Analysis of configuration difficulties:
- lintOnSave: Whether to enable eslint validation every time you save code in the development environment
false: 关闭每次保存都进行检测
true: 开启每次保存都进行检测,效果与warning一样
warning: 开启每次保存都进行检测,lint 错误将显示到控制台命令行,而且编译并不会失败。
error: 开启每次保存都进行检测,lint 错误将显示到浏览器页面上,且编译失败。
default: 同’error’
- productionSourceMap: Set the source map of the production environment on and off
usage:
module.exports = {
publicPath: './', // 基本路径
outputDir: 'dist', // 输出文件目录
assetsDir: './assets',
indexPath: 'index.html',
filenameHashing: true, // 生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存
lintOnSave: false, // eslint-loader 是否在保存的时候检查
productionSourceMap: true, // 生产环境是否生成 sourceMap 文件
}
What is a source map?
Source map Literally translated is a resource map. Therefore, the role of the source map is to locate. The location of the browser console output statement in the project file when the source map is located.
E.g:
After packing:
Without productionSourceMap turned on:
opened:
It can be seen that after opening productionSourceMap, the browser console clearly tells us that the output statement of the test result is in line 20 of main.js. That's what the source map is for, and it's very useful when developers make mistakes.
Let's take a look at the comparison of project files packaged with productionSourceMap turned on/off:
opened:
closed:
It can be seen that after the productionSourceMap is turned on, the packaged and generated js files have a .map file. It should be noted here that only js has a .map file.
This concludes the basic configuration explanation.
Switching between development and production environments
module.exports = {
configureWebpack: config => {
if (process.env.NODE_ENV === 'production') {
// 为生产环境修改配置...
} else {
// 为开发环境修改配置...
}
}
}
The difference between configureWebpack and chainWebpack
configureWebpack
The same chainWebpack
as the one, the only difference is that they modify the webpack configuration differently:
chainWebpack
Modify the default webpack configuration in the form of chain programmingconfigureWebpack
Modify the default webpack configuration by manipulating objects
(1) chainWebpack method:
module.exports = {
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(options => {
// 修改他的选项
return options
})
}
}
(2) The following are all configureWebpack
configuration methods:
configureWebpack object form :
module.exports = {
configureWebpack:{
resolve: {
// 别名配置
alias: {
'assets': '@/assets',
'common': '@/common',
'components': '@/components',
'network': '@/network',
'configs': '@/configs',
'views': '@/views',
'plugins': '@/plugins',
}
}
}
}
configureWebpack function form :
module.exports = {
configureWebpack:(config) => {
if (process.env.NODE_ENV === 'production') {
// 为生产环境修改配置...
config.mode = 'production'
} else {
// 为开发环境修改配置...
config.mode = 'development'
}
// 开发生产共同配置别名
Object.assign(config.resolve, {
alias: {
'@': path.resolve(__dirname, './src'),
'assets': path.resolve(__dirname, './src/assets'),
'common': path.resolve(__dirname, './src/common'),
'components': path.resolve(__dirname, './src/components'),
'network': path.resolve(__dirname, './src/network'),
'configs': path.resolve(__dirname, './src/configs'),
'views': path.resolve(__dirname, './src/views'),
'plugins': path.resolve(__dirname, './src/plugins'),
}
})
}
}
process.env.NODE_ENV details
Reference: https://www.jianshu.com/p/f4638f5df1c7