您的位置:首页 > 科技 > 能源 > vue.config.js 配置

vue.config.js 配置

2024/10/5 23:21:05 来源:https://blog.csdn.net/a123456234/article/details/140966496  浏览:    关键词:vue.config.js 配置

vue.config.js 文件是 Vue CLI 项目中的全局配置文件,它允许你以 JavaScript 的形式来配置构建选项,而不是通过命令行参数或者 .vue-clirc 的 JSON 格式。
官方文档: https://cli.vuejs.org/zh/config/#全局-cli-配置

基础配置

  1. publicPath

    • 设置构建好的文件被部署后的公共路径。
    module.exports = {publicPath: process.env.NODE_ENV === 'production' ? '/my-app/' : '/',
    };
    
  2. outputDir

    • 构建输出的目录,默认是 dist
    module.exports = {outputDir: 'dist',
    };
    
  3. assetsDir

    • 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下)。
    module.exports = {assetsDir: "static",
    };
    
  4. indexPath

    • 指定生成的 index.html 的输出路径 (相对于 outputDir)。也可以是一个绝对路径。默认 'index.html'
    module.exports = {indexPath: "index.html",
    };
    
  5. productionSourceMap

    • 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
    module.exports = {productionSourceMap: false,
    };
    
  6. filenameHashing

    • 默认情况下,生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存。然而,这也要求 index 的 HTML 是被 Vue CLI 自动生成的。如果你无法使用 Vue CLI 生成的 index HTML,你可以通过将这个选项设为 false 来关闭文件名哈希。默认 false
    module.exports = {filenameHashing: false,
    };
    
  7. lintOnSave

    • 是否开启 eslint 保存检测,有效值:ture | false | 'error'
    • 设置为 true'warning' 时,eslint-loader 会将 lint 错误输出为编译警告。默认情况下,警告仅仅会被输出到命令行,且不会使得编译失败。
    • 如果你希望让 lint 错误在开发时直接显示在浏览器中,你可以使用 lintOnSave: 'default'。这会强制 eslint-loaderlint 错误输出为编译错误,同时也意味着 lint 错误将会导致编译失败。
    • 设置为 error 将会使得 eslint-loaderlint 警告也输出为编译错误,这意味着 lint 警告将会导致编译失败。
    • 设置 false 关闭 lint 警告
    module.exports = {lintOnSave: false,
    };
    
  8. runtimeCompiler

    • 是否使用包含运行时编译器的 Vue 构建版本。设置为 true 后你就可以在 Vue 组件中使用 template 选项了,但是这会让你的应用额外增加 10kb 左右。默认 false
    module.exports = {runtimeCompiler: false,
    };
    

    更多细节可查阅: Runtime + Compiler vs. Runtime only

  9. transpileDependencies

    • 默认情况下 babel-loader 会忽略所有 node_modules 中的文件。你可以启用本选项,以避免构建后的代码中出现未转译的第三方依赖。

    不过,对所有的依赖都进行转译可能会降低构建速度。如果对构建性能有所顾虑,你可以只转译部分特定的依赖:给本选项传一个数组,列出需要转译的第三方包包名或正则表达式即可。

    module.exports = {transpileDependencies: false,
    };
    
  10. crossorigin

    • 设置生成的 HTML 中 <link rel="stylesheet"><script> 标签的 crossorigin 属性。

    需要注意的是该选项仅影响由 html-webpack-plugin 在构建时注入的标签 - 直接写在模版 (public/index.html) 中的标签不受影响。

    crossorigin: 如果配置了该属性,会让浏览器启用CORS检查(判断响应头中Access-Control-Allow-Origin是否与当前文档同源),如果检查不通过,则浏览器拒绝执行代码。

    stylesheet: 导入样式表。link 标签使用了 rel="stylesheet" 表示该文件是一份样式表文件。可以让 HTML 页面具有更好的外观和布局。

    module.exports = {crossorigin: false,
    };
    
  11. integrity

    • 在生成的 HTML 中的 <link rel="stylesheet"><script> 标签上启用 Subresource Integrity (SRI)。如果你构建后的文件是部署在 CDN 上的,启用该选项可以提供额外的安全性。

    • 需要注意的是该选项仅影响由 html-webpack-plugin 在构建时注入的标签 - 直接写在模版 (public/index.html) 中的标签不受影响。

    • 当启用 SRI 时,preload resource hints 会被禁用,因为 Chrome 的一个 bug 会导致文件被下载两次。

    module.exports = {integrity: false,
    };
    
  12. configureWebpack

    • 如果这个值是一个对象,则会通过 w[]ebpack-merge](https://github.com/survivejs/webpack-merge) 合并到最终的配置中。
    • 如果这个值是一个函数,则会接收被解析的配置作为参数。该函数既可以修改配置并不返回任何东西,也可以返回一个被克隆或合并过的配置版本。更多细节请查阅 配合 webpack > 简单的配置方式
    module.exports = {configureWebpack: {}, // ()=> {}
    };
    
  13. chainWebpack

    • 是一个函数,会接收一个基于 webpack-chain 的 ChainableConfig 实例。允许对内部的 webpack 配置进行更细粒度的修改。更多细节可查阅:配合 webpack > 链式操作
    module.exports = {chainWebpack: ()=> {}
    };
    
  14. css.modules

    • 从 v4 起已弃用,请使用 css.requireModuleExtension。 在 v3 中,这个选项含义与 css.requireModuleExtension 相反。
    module.exports = {css: {modules: false,}
    };
    
  15. pages

    • 定义多个入口页面。
    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',// 片段注入到页面的地点,// 可以是 (head / end / body / top / bottom)chunks: ['chunk-vendors', 'chunk-common', 'index']},otherpage: { // 新增的入口// page 的入口entry: 'src/otherpage/main.js',// 模板来源template: 'public/otherpage.html',  // 或者 'public/otherpage/otherpage.html'// 在 dist/otherpage.html 的输出filename: 'otherpage.html',// 当使用 title 选项时,// template 中的 <title> 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>title: 'Other Page',// 片段注入到页面的地点,// 可以是 (head / end / body / top / bottom)chunks: ['chunk-vendors', 'chunk-common', 'otherpage']}}
    }
    

    参考链接: vue.config.js 配置多入口文件

配置 devserve

module.exports = {devServer: {host: '0.0.0.0', // 让你的服务器可以被外部访问port: 8080, // 端口https: false, // 不使用 HTTP 提供服务hot: true, //  模块热替换open: true, // 打开浏览器client:{overlay: { // 当出现编译错误或警告时,在浏览器中显示全屏覆盖。warnings: true,errors: true},progress: true, // 在浏览器中以百分比形式打印编译进度。},headers: { // 设置请求头'X-Custom-Header': 'value'},compress: true, // 启用 gzip 压缩proxy: {'/api': { // 对 /api 的请求会将请求代理到 http://localhost:4000。target: 'http://localhost:4000',changeOrigin: true, // 使 Origin 请求头中的主机名变为目标 URL 的主机名secure: false, // 不验证 SSL 证书logLevel: 'warn', // 代理的日志级别ws: true, // 使用 WebSockets 作为服务器pathRewrite: { // 重写路径'^/api': ''},router: function(req) {if (req.url.startsWith('/api')) {return '/api';}return false;},context: ['/api'],bypass: function(req) {if (req.headers.accept.indexOf('html') !== -1) {return '/index.html';}}}},contentBase: './public', // 开发服务器提供的静态文件目录historyApiFallback: true, // 是否启用 HTML5 history API 的回退before: function(app, server) {// 在服务器启动之前执行的函数},after: function(app, server) {// 在服务器启动之后执行的函数},setupMiddlewares: true,  // 设置中间件}
};

参考链接: vue.config.js 配置 devserve 配置

配置 configureWebpack 和 chainWebpack

configureWebpack

configureWebpack 允许你在 Vue CLI 项目中直接修改 Webpack 的配置。它可以通过一个对象或一个函数来实现。如果你使用的是一个函数,那么它会接收默认的 Webpack 配置作为参数,并且你应该返回一个修改过的配置对象。

配置示例:

const path = require("path");
const TerserPlugin = require("terser-webpack-plugin");
const WebpackObfuscator = require('webpack-obfuscator');function resolve(dir) {return path.join(__dirname, dir);
}
const name = '浏览器网页标题';
module.exports = {configureWebpack: (config) => {config.name = name,config.resolve = {...config.resolve,alias: {"@": resolve("src"), // 配置别名 @'vue': path.resolve(__dirname, './', 'node_modules', 'vue') // 去重vue包,多个vue包会导致element-ui 里的 table 组件不生效}},config.optimization = {...config.minimizer,minimizer: [new TerserPlugin({terserOptions: {compress: {drop_console: true, // 去除 console.logdrop_debugger: true, // 去除 debugger},},}),]}if (process.env.NODE_ENV === 'production') {config.plugins.push(new WebpackObfuscator({// 压缩代码compact: true,// 是否启用控制流扁平化(降低1.5倍的运行速度)controlFlowFlattening: false,// 随机的死代码块(增加了混淆代码的大小)deadCodeInjection: false,// 此选项几乎不可能使用开发者工具的控制台选项卡debugProtection: false,// 如果选中,则会在“控制台”选项卡上使用间隔强制调试模式,从而更难使用“开发人员工具”的其他功能。debugProtectionInterval: false,// 通过用空函数替换它们来禁用console.log,console.info,console.error和console.warn。这使得调试器的使用更加困难。disableConsoleOutput: true,// 标识符的混淆方式 hexadecimal(十六进制) mangled(短标识符)identifierNamesGenerator: 'hexadecimal',log: false,// 是否启用全局变量和函数名称的混淆renameGlobals: false,// 通过固定和随机(在代码混淆时生成)的位置移动数组。这使得将删除的字符串的顺序与其原始位置相匹配变得更加困难。如果原始源代码不小,建议使用此选项,因为辅助函数可以引起注意。rotateStringArray: true,// 混淆后的代码,不能使用代码美化,同时需要配置 cpmpat:true;selfDefending: true,// 删除字符串文字并将它们放在一个特殊的数组中stringArray: true,rotateUnicodeArray: true,//  stringArrayEncoding: 'base64',stringArrayEncoding: ['base64'],stringArrayThreshold: 0.75,// 允许启用/禁用字符串转换为unicode转义序列。Unicode转义序列大大增加了代码大小,并且可以轻松地将字符串恢复为原始视图。建议仅对小型源代码启用此选项。unicodeEscapeSequence: false,// 允许启用/禁用字符串转换为unicode转义序列。Unicode转义序列大大增加了代码大小,并且可以轻松地将字符串恢复为原始视图。建议仅对小型源代码启用此选项。transformObjectKeys: true,}))}},
}

chainWebpack

chainWebpack 是 Vue CLI 提供的一种更强大的方式来修改 Webpack 的配置。与 configureWebpack 不同,chainWebpack 使用 Webpack Chain API,它允许你以一种声明式的方式来修改 Webpack 配置

配置示例:

const path = require("path");
module.exports = {chainWebpack: (config) => {// 修改 HTML 插件的选项config.plugin('html').tap(args => {args[0].title = 'My App';return args;});// 修改模块规则config.module.rule('images').test(/\.(png|jpe?g|gif|webp)(\?.*)?$/).use('url-loader').loader('url-loader').options({limit: 10000,name: 'img/[name].[hash:7].[ext]'});// 去除 debuggerconfig.when(process.env.NODE_ENV === 'production', config => {config.optimization.minimize(true);config.optimization.minimizer('terser').tap(args => {args[0].terserOptions.compress.drop_debugger = true;return args;});});// 添加别名config.resolve.alias.set('@components', resolve('src/components')).set('@assets', resolve('src/assets'));// 添加额外的插件config.plugin('define').tap(args => {args[0]['process.env'].VUE_APP_VERSION = JSON.stringify(process.env.VUE_APP_VERSION || '');return args;});// 修改输出选项config.output.filename('[name].[contenthash].js');},
};function resolve(dir) {return path.join(__dirname, dir);
}

参考链接: vue.config.js 配置configureWebpack 和 chainWebpack 以及一些常用配置

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com