vue-cli4中webpack配置

3,653 阅读2分钟

创建与package.json同级的vue.config.js文件。

publicPath:项目在子路径运行

一般运行在根路径https://www.my-app.com/,如果想运行在子路径https://www.my-app.com/my-app/。设置 publicPath/my-app/

有些场景不适用

  • 当使用基于 HTML5 history.pushState 的路由时;
  • 当使用 pages 选项构建多页面应用时。
// 生产环境设在子路径,开发环境设在根路径
module.exports = {
  publicPath: process.env.NODE_ENV === 'production'
    ? '/production-sub-path/'
    : '/'
}

outputDir:指定 build命令生成目录位置

  • Default: 'dist'

该目录在构建之前会被清除 (传入 --no-clean 可关闭该行为)。

assetsDir:指定静态资源 (js、css、img、fonts) 相对于 outputDir 的目录

indexPath:指定index.html相对于 outputDir 的路径

lintOnSave:通过 eslint-loader 在保存时检测代码

@vue/cli-plugin-eslint 安装之后生效。

  • true 或 'warning'---将 lint 错误作为编译警告输出到命令行,不会使编译失败。
  • 'default'-----------将 lint 错误输出为编译错误,导致编译失败。
  • 'error'-------------将 lint 警告输出为编译错误,导致编译失败。

禁用 eslint-loader

module.exports = {
  lintOnSave: process.env.NODE_ENV !== 'production'
}

productionSourceMap:构建处理前代码和处理后代码之间的桥梁,方便开发人员的错误定位。

Default: true(开启)
用法:建议开启,生产模式下关闭

css.sourceMap:是否为 CSS 开启 source map,用法同上

devServer:开发环境的设置,不用于生产环境

devServer: {
        port: 8080,
        progress: true,  // 显示打包的进度条
        contentBase: distPath,  // 根目录
        open: true,  // 自动打开浏览器
        compress: true,  // 启动 gzip 压缩

        // 设置代理
        proxy: {
            // 将本地 /api/xxx 代理到 localhost:3000/api/xxx
            '/api': 'http://localhost:3000',

            // 将本地 /api2/xxx 代理到 localhost:3000/xxx
            '/api2': {
                target: 'http://localhost:3000',
                pathRewrite: {
                    '/api2': ''
                }
            }
        }
    }

vue如何实现跨域?

本地开发环境的话配置devServer.proxy,生产环境需要nginx以及后端代码处理。

devServer.proxy配置跨域-GitHub链接