vue.config.js配置详解
文章目录
简介
vue.config.js 是一个可选的配置文件,如果项目的 (和 package.json 同级的) 根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载。你也可以使用 package.json 中的 vue 字段,但是注意这种写法需要你严格遵照 JSON 的格式来写。
这个文件应该导出一个包含了选项的对象:
// vue.config.js
/**
* @type {import('@vue/cli-service').ProjectOptions}
*/
module.exports = {
// 选项...
}
或者,你也可以使用 @vue/cli-service 提供的 defineConfig 帮手函数,以获得更好的类型提示:
// vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
// 选项
})
publicPath
- Type:
string - Default:
/
由于在Vue CLI 3.3 之后baseUrl已被弃用,使用publicPath进行替代。
默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上,例如 https://www.my-app.com/,此时publicPath的值为/如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.my-app.com/my-app/,则设置 publicPath 为 /my-app/。
相对 publicPath 的限制
相对路径的
publicPath有一些使用上的限制。在以下情况下,应当避免使用相对publicPath:
- 当使用基于 HTML5
history.pushState的路由时;- 当使用
pages选项构建多页面应用时。
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? '/admin/' : '/'
}
outputDir
- Type:
string - Default:
'dist'
在Vue的项目中当运行npm run build对项目进行生产环境打包时生成的文件夹通常命名为dist可以通过更改此配置来更改文件夹的名称
提示
请始终使用
outputDir而不要修改 webpack 的output.path。
module.exports = {
outputDir: 'dist'
}
assetsDir
-
Type:
string -
Default:
''放置生成的静态资源 (
js、css、img、fonts) 的 (相对于outputDir的) 目录。
提示
从生成的资源覆写
filename或chunkFilename时,assetsDir会被忽略。
module.exports = {
assetsDir: 'static'
}
indexPath
-
Type:
string -
Default:
'index.html'指定生成的
index.html的输出路径 (相对于outputDir)。也可以是一个绝对路径。
module.exports = {
assetsDir: 'index.html'
}
filenameHashing
-
Type:
boolean -
Default:
true默认情况下,生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存。然而,这也要求 index 的 HTML 是被 Vue CLI 自动生成的。如果你无法使用 Vue CLI 生成的 index HTML,你可以通过将这个选项设为
false来关闭文件名哈希。
module.exports = {
filenameHashing:false
}
pages
-
Type:
Object -
Default:
undefined在 multi-page 模式下构建应用。每个“page”应该有一个对应的 JavaScript 入口文件。其值应该是一个对象,对象的 key 是入口的名字,value 是:
- 一个指定了
entry,template,filename,title和chunks的对象 (除了entry之外都是可选的); - 或一个指定其
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'
}
}
提示
当在 multi-page 模式下构建时,webpack 配置会包含不一样的插件 (这时会存在多个
html-webpack-plugin和preload-webpack-plugin的实例)。如果你试图修改这些插件的选项,请确认运行vue inspect。
lintOnSave
- Type:
boolean|'warning'|'default'|'error' - Default:
'default'
检验语法规范,只有当安装了@vue/cli-plugin-eslint之后才会生效。
设置为 true 或 'warning' 时,eslint-loader 会将 lint 错误输出为编译警告。默认情况下,警告仅仅会被输出到命令行,且不会使得编译失败。
如果你希望让 lint 错误在开发时直接显示在浏览器中,你可以使用 lintOnSave: 'default'。这会强制 eslint-loader 将 lint 错误输出为编译错误,同时也意味着 lint 错误将会导致编译失败。
设置为 error 将会使得 eslint-loader 把 lint 警告也输出为编译错误,这意味着 lint 警告将会导致编译失败。
或者,你也可以通过设置让浏览器 overlay 同时显示警告和错误:
// vue.config.js
module.exports = {
devServer: {
overlay: {
warnings: true,
errors: true
}
}
}
当 lintOnSave 是一个 truthy 的值时,eslint-loader 在开发和生产构建下都会被启用。如果你想要在生产构建时禁用 eslint-loader,你可以用如下配置:
// vue.config.js
module.exports = {
lintOnSave: process.env.NODE_ENV !== 'production'
}
runtimeCompiler
-
Type:
boolean -
Default:
false是否使用包含运行时编译器的
Vue构建版本。设置为true后你就可以在Vue组件中使用template选项了,但是这会让你的应用额外增加 10kb 左右。
transpileDependencies
-
Type:
boolean | Array<string | RegExp> -
Default:
false默认情况下
babel-loader会忽略所有node_modules中的文件。你可以启用本选项,以避免构建后的代码中出现未转译的第三方依赖。不过,对所有的依赖都进行转译可能会降低构建速度。如果对构建性能有所顾虑,你可以只转译部分特定的依赖:给本选项传一个数组,列出需要转译的第三方包包名或正则表达式即可。
// vue.config.js
module.exports = {
transpileDependencies: [
'vue-echarts',
'resize-detector'
]
}
productionSourceMap
-
Type:
boolean -
Default:
true如果你不需要生产环境的 source map,可以将其设置为
false以加速生产环境构建。
crossorigin
-
Type:
string -
Default:
undefined设置生成的 HTML 中
<link rel="stylesheet">和<script>标签的crossorigin属性。需要注意的是该选项仅影响由
html-webpack-plugin在构建时注入的标签 - 直接写在模版 (public/index.html) 中的标签不受影响。更多细节可查阅: CORS settings attributes
configureWebpack
-
Type:
Object | Function如果这个值是一个对象,则会通过 webpack-merge 合并到最终的配置中。
如果这个值是一个函数,则会接收被解析的配置作为参数。该函数既可以修改配置并不返回任何东西,也可以返回一个被克隆或合并过的配置版本。
对象形式
configureWebpack:{
resolve: {
// 别名配置
alias: {
'assets': '@/assets',
'common': '@/common',
'components': '@/components',
'network': '@/network',
'configs': '@/configs',
'views': '@/views',
'plugins': '@/plugins',
}
}
},
对象形式可以为某些特定文件夹区别名
也可以写成如下形式:
configureWebpack: {
//在webpack的name字段中提供应用的标题,这样就可以在index.html中访问它来注入正确的标题。
name: name,
resolve: {
alias: {
'@': resolve('src'),
'@crud': resolve('src/components/Crud')
}
}
},
函数形式
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'),
}
})
},
chainWebpack
-
Type:
Function是一个函数,会接收一个基于 webpack-chain 的
ChainableConfig实例。允许对内部的 webpack 配置进行更细粒度的修改。
chainWebpack:(config)=>{
config.plugins.delete('preload'); // TODO: need test
config.plugins.delete('prefetch'); // TODO: need test
config.plugin('html').tap(args=>{
args[0].title=name
return args
})
config.resolve.alias
.set('@',resolve('./src'))
.set('components',resolve('./src/components'))
.set('views',resolve('./src/views'))
.set('assets',resolve('./src/assets'))
}
或者
chainWebpack(config) {
//下面两行代码是移除preload(预载) 与 prefetch (预取)
//vue 脚手架默认开启了 preload 与 prefetch,当我们项目很大时,这个就成了首屏加载的最大元凶了。
//先简单了解一下 preload 与 prefetch。
//preload 与 prefetch 都是一种资源预加载机制;
//preload 是预先加载资源,但并不执行,只有需要时才执行它;
//prefetch 是意图预获取一些资源,以备下一个导航/页面使用;
//preload 的优先级高于 prefetch。
config.plugins.delete('preload') // TODO: need test
config.plugins.delete('prefetch') // TODO: need test
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
// set preserveWhitespace
config.module
.rule('vue')
.use('vue-loader')
.loader('vue-loader')
.tap(options => {
options.compilerOptions.preserveWhitespace = true
return options
})
.end()
config
// https://webpack.js.org/configuration/devtool/#development
.when(process.env.NODE_ENV === 'development',
config => config.devtool('cheap-source-map')
)
config
.when(process.env.NODE_ENV !== 'development',
config => {
config
.plugin('ScriptExtHtmlWebpackPlugin')
.after('html')
.use('script-ext-html-webpack-plugin', [{
// `runtime` must same as runtimeChunk name. default is `runtime`
inline: /runtime\..*\.js$/
}])
.end()
config
.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
libs: {
name: 'chunk-libs',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: 'initial' // only package third parties that are initially dependent
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true
}
}
})
config.optimization.runtimeChunk('single')
}
)
},
devServer
-
Type:
Object所有
webpack-dev-server的选项都支持。注意:- 有些值像
host、port和https可能会被命令行参数覆写。 - 有些值像
publicPath和historyApiFallback不应该被修改,因为它们需要和开发服务器的 publicPath 同步以保障正常的工作。
- 有些值像
devServer: {
// host: 'localhost',
port: 8090, //项目运行的端口号
open: true, //配置自动启动浏览器
}
devServer.proxy
-
Type:
string | Object如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过
vue.config.js中的devServer.proxy选项来配置。devServer.proxy可以是一个指向开发环境 API 服务器的字符串:
devServer: {
// host: 'localhost',
port: 8090, //项目运行的端口号
open: true, //配置自动启动浏览器
proxy: {
"/opAdmin": {
target: "http://116.66.65.193:8081", //对应服务端的接口地址
changeOrigin: true, // 开启跨域
pathRewrite: {
"^/opAdmin": "/opAdmin" //将以 /opAdmin 开头的接口重写http://116.66.65.193:8081/opAdmin ,调用时直接以 /opAdmin开头即表示调用http://116.66.65.193:8081/opAdmin
// "^/opAdmin": "/" //将以 /opAdmin 开头的接口重写http://116.66.65.193:8081/ ,调用时直接以 /opAdmin开头即表示调用http://116.66.65.193:8081/
// "^/opAdmin": "" //将以 /opAdmin 开头的接口重写http://116.66.65.193:8081 ,调用时直接以 /opAdmin开头即表示调用http://116.66.65.193:8081
}
},
"/DoorStatus": {
target: "http://47.99.11.102:8088", //对应服务端的接口地址
changeOrigin: true
}
}
}

Vue.config.js 是 Vue 项目中的配置文件,用于自定义构建设置。它包含各种配置选项,如公共路径、输出目录、静态资源处理等。在多页应用中,还可以配置每个页面的入口、模板等。此外,还能设置 ESLint 的校验规则,以及在开发和生产环境下的源码映射。通过 alias,可以为特定文件夹设置别名。函数形式的配置允许对 webpack 配置进行深度定制。若需在开发环境将 API 请求代理到另一服务器,可通过 devServer.proxy 配置。
9929

被折叠的 条评论
为什么被折叠?



