Vue CLI(三)vue.config.js 配置文件详解

vue.config.js 常用参数详解

1. 基本结构

// vue.config.js
module.exports = {
  // 这里填写各种配置项
}

2. 详细参数列表及说明

2.1 publicPath

  • 作用:指定应用的部署路径(资源的基础路径)。
  • 默认'/'
  • 常用场景:部署到子目录时需设置。
publicPath: process.env.NODE_ENV === 'production' ? '/sub-path/' : '/'

2.2 outputDir

  • 作用:指定打包输出目录。
  • 默认'dist'
outputDir: 'dist'

2.3 assetsDir

  • 作用:静态资源(js、css、img、fonts)存放目录,相对于 outputDir。
  • 默认''
assetsDir: 'static'

2.4 indexPath

  • 作用:指定生成的 index.html 的输出路径(相对于 outputDir)。
  • 默认'index.html'
indexPath: 'index.html'

2.5 filenameHashing

  • 作用:是否在生成的静态资源文件名添加 hash,防止缓存。
  • 默认true
filenameHashing: true

2.6 pages

  • 作用:多页面配置。
  • 类型:对象
pages: {
  index: {
    entry: 'src/main.js',
    template: 'public/index.html',
    filename: 'index.html',
    title: '首页',
    chunks: ['chunk-vendors', 'chunk-common', 'index']
  },
  // 其他页面...
}

2.7 lintOnSave

  • 作用:保存时是否进行代码校验(ESLint)。
  • 默认true
  • 可选值truefalse'error'
lintOnSave: false

2.8 runtimeCompiler

  • 作用:是否使用包含编译器的 Vue 构建版本(允许在运行时编译模板)。
  • 默认false
runtimeCompiler: true

2.9 transpileDependencies

  • 作用:需要通过 Babel 显式转译的第三方依赖。
  • 类型:数组
transpileDependencies: ['some-es6-package']

2.10 productionSourceMap

  • 作用:生产环境是否生成 source map。
  • 默认true
productionSourceMap: false

2.11 crossorigin

  • 作用:设置 <link rel="stylesheet"> 和 <script> 标签的 crossorigin 属性。
  • 可选值'anonymous''use-credentials'false
crossorigin: 'anonymous'

2.12 integrity

  • 作用:是否为构建的资源启用 Subresource Integrity(SRI)。
  • 默认false
integrity: true

2.13 configureWebpack

  • 作用:直接修改 webpack 配置(对象或函数)。
  • 类型:对象或函数
configureWebpack: {
  plugins: [
    // 自定义插件
  ]
}

或者:

configureWebpack: config => {
  config.plugins.push(/* 插件 */)
}

2.14 chainWebpack

  • 作用:使用 webpack-chain 细粒度修改 webpack 配置。
chainWebpack: config => {
  config.module
    .rule('svg')
    .test(/\.svg$/)
    .use('svg-loader')
    .loader('svg-loader')
}

2.15 css 相关配置

css: {
  // 是否提取 CSS 到单独文件
  extract: true,
  // 是否开启 CSS source map
  sourceMap: false,
  // CSS loader 配置
  loaderOptions: {
    css: {},
    less: {},
    sass: {},
    scss: {},
    stylus: {},
    postcss: {}
  },
  // 是否启用 CSS modules
  requireModuleExtension: false
}

2.16 devServer 开发服务器配置

devServer: {
  open: true, // 自动打开浏览器
  host: '0.0.0.0', // 允许外部访问
  port: 8080, // 端口
  https: false, // 是否启用 https
  hotOnly: false, // 热更新
  proxy: { // 代理配置
    '/api': {
      target: 'http://localhost:3000',
      changeOrigin: true,
      pathRewrite: { '^/api': '' }
    }
  }
}

2.17 pluginOptions

  • 作用:第三方插件的自定义配置。
pluginOptions: {
  'style-resources-loader': {
    preProcessor: 'scss',
    patterns: []
  }
}

3. 其他参数

  • pwa:PWA 支持配置
  • parallel:是否使用多线程压缩
  • devtool:自定义 source map 生成方式

4. 完整示例

module.exports = {
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  indexPath: 'index.html',
  filenameHashing: true,
  lintOnSave: false,
  runtimeCompiler: false,
  transpileDependencies: [],
  productionSourceMap: false,
  crossorigin: undefined,
  integrity: false,
  configureWebpack: {},
  chainWebpack: config => {},
  css: {
    extract: true,
    sourceMap: false,
    loaderOptions: {},
    requireModuleExtension: false
  },
  devServer: {
    open: true,
    host: 'localhost',
    port: 8080,
    https: false,
    hotOnly: false,
    proxy: {},
  },
  pluginOptions: {}
}

参考文档


总结

  • vue.config.js 是 Vue CLI 项目的总配置文件,参数丰富,可高度定制项目行为。
  • 常用参数如 publicPathoutputDirdevServercss 等。
  • webpack 相关配置推荐用 configureWebpack 和 chainWebpack
  • 多页面开发用 pages
  • 开发服务器、代理用 devServer

5. 进阶参数与用法

5.1 pwa

  • 作用:配置 PWA(渐进式网页应用)相关参数,需要安装 @vue/cli-plugin-pwa
  • 常用配置
pwa: {
  name: '我的应用',
  themeColor: '#4DBA87',
  msTileColor: '#000000',
  appleMobileWebAppCapable: 'yes',
  appleMobileWebAppStatusBarStyle: 'black',
  manifestOptions: {
    background_color: '#42b983'
  }
}

5.2 parallel

  • 作用:是否使用多进程处理 Babel 或 TypeScript 以加快构建速度。
  • 默认:根据系统 CPU 核数自动决定。
parallel: true

5.3 devtool

  • 作用:自定义 source map 生成方式(覆盖默认 source map 配置)。
  • 常用值source-mapcheap-module-source-mapeval-source-map 等。
configureWebpack: {
  devtool: 'source-map'
}

5.4 crossorigin/integrity

  • 作用:安全相关,通常用于 CDN 部署。
crossorigin: 'anonymous',
integrity: true

5.5 loaderOptions(css)

  • 作用:为各类 CSS 预处理器传递参数。
css: {
  loaderOptions: {
    less: {
      modifyVars: {
        'primary-color': '#42b983'
      },
      javascriptEnabled: true
    },
    sass: {
      additionalData: `@import "@/styles/variables.scss";`
    }
  }
}

6. 高级配置技巧

6.1 环境变量与配置

  • 你可以在项目根目录下创建 .env 文件(如 .env.development.env.production),并在 vue.config.js 中读取环境变量:
publicPath: process.env.VUE_APP_PUBLIC_PATH
  • 在代码中通过 process.env.VUE_APP_XXX 访问自定义环境变量。

6.2 配置 SVG 图标自动导入

chainWebpack: config => {
  const svgRule = config.module.rule('svg')
  svgRule.uses.clear()
  svgRule
    .use('svg-sprite-loader')
    .loader('svg-sprite-loader')
    .options({ symbolId: 'icon-[name]' })
}

6.3 配置全局样式/变量

css: {
  loaderOptions: {
    scss: {
      additionalData: `@import "@/styles/global.scss";`
    }
  }
}

6.4 配置代理(解决跨域)

devServer: {
  proxy: {
    '/api': {
      target: 'http://backend.server',
      changeOrigin: true,
      pathRewrite: { '^/api': '' }
    }
  }
}

6.5 配置多页面应用

pages: {
  index: {
    entry: 'src/main.js',
    template: 'public/index.html',
    filename: 'index.html'
  },
  admin: {
    entry: 'src/admin/main.js',
    template: 'public/admin.html',
    filename: 'admin.html'
  }
}

7. 常见问题与解决方案

7.1 webpack 配置冲突

  • 使用 configureWebpack 适合简单合并,chainWebpack 适合复杂定制。

7.2 代理失效

  • 检查 devServer.proxy 配置,端口、路径是否正确,changeOrigin 是否为 true

7.3 CSS 全局变量失效

  • 确认 loaderOptions 的写法是否正确,路径是否有效。

7.4 构建速度慢

  • 关闭 productionSourceMap
  • 启用 parallel
  • 精简依赖,合理配置 transpileDependencies

8. vue.config.js 完整示例(进阶)

module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? '/sub-path/' : '/',
  outputDir: 'dist',
  assetsDir: 'static',
  indexPath: 'index.html',
  filenameHashing: true,
  lintOnSave: process.env.NODE_ENV !== 'production',
  runtimeCompiler: true,
  transpileDependencies: ['vue-echarts', 'resize-detector'],
  productionSourceMap: false,
  crossorigin: 'anonymous',
  integrity: true,
  configureWebpack: {
    devtool: 'source-map',
    plugins: [
      // 你的自定义插件
    ]
  },
  chainWebpack: config => {
    config.module
      .rule('svg')
      .test(/\.svg$/)
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({ symbolId: 'icon-[name]' })
  },
  css: {
    extract: true,
    sourceMap: false,
    loaderOptions: {
      scss: {
        additionalData: `@import "@/styles/global.scss";`
      }
    },
    requireModuleExtension: false
  },
  devServer: {
    open: true,
    host: 'localhost',
    port: 8080,
    https: false,
    hotOnly: false,
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        pathRewrite: { '^/api': '' }
      }
    }
  },
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'scss',
      patterns: [path.resolve(__dirname, 'src/styles/variables.scss')]
    }
  },
  pwa: {
    name: '我的PWA应用',
    themeColor: '#42b983',
    manifestOptions: {
      background_color: '#42b983'
    }
  },
  parallel: true
}

10. 高级实用技巧

10.1 自定义环境变量的应用

你可以在 .env 文件中定义变量(如 .env.production):

VUE_APP_API_BASE=https://api.example.com

在 vue.config.js 和项目代码中都可以通过 process.env.VUE_APP_API_BASE 访问。


10.2 构建体积优化

  • 只打包需要的 locale(以 moment.js 为例):
configureWebpack: {
  plugins: [
    new webpack.IgnorePlugin({
      resourceRegExp: /^\.\/locale$/,
      contextRegExp: /moment$/
    })
  ]
}
  • 开启 gzip 压缩(需安装 compression-webpack-plugin):
const CompressionWebpackPlugin = require('compression-webpack-plugin');

configureWebpack: config => {
  if (process.env.NODE_ENV === 'production') {
    config.plugins.push(
      new CompressionWebpackPlugin({
        algorithm: 'gzip',
        test: /\.(js|css|html|svg)$/,
        threshold: 10240,
        minRatio: 0.8
      })
    );
  }
}

10.3 多语言(i18n)集成

如果用 vue-i18n,可通过 pluginOptions 配置:

pluginOptions: {
  i18n: {
    locale: 'zh',
    fallbackLocale: 'en',
    localeDir: 'locales',
    enableInSFC: true
  }
}

10.4 配置别名 alias

方便你在项目中用 @ 或自定义别名引用路径:

const path = require('path');

configureWebpack: {
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@components': path.resolve(__dirname, 'src/components')
    }
  }
}

10.5 打包分析

定位包体积问题,推荐集成 webpack-bundle-analyzer

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

configureWebpack: config => {
  if (process.env.NODE_ENV === 'production') {
    config.plugins.push(new BundleAnalyzerPlugin());
  }
}

11. 常见场景实战配置

11.1 配置全局 SASS/LESS 变量

css: {
  loaderOptions: {
    scss: {
      additionalData: `@import "~@/styles/variables.scss";`
    }
  }
}

11.2 CDN 引入第三方库

减小打包体积,将常用库通过 CDN 引入:

configureWebpack: {
  externals: {
    vue: 'Vue',
    'vue-router': 'VueRouter',
    axios: 'axios'
  }
},
chainWebpack: config => {
  config.plugin('html').tap(args => {
    args[0].cdn = {
      css: [],
      js: [
        'https://cdn.jsdelivr.net/npm/vue@2/dist/vue.min.js',
        'https://cdn.jsdelivr.net/npm/vue-router@3/dist/vue-router.min.js',
        'https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js'
      ]
    }
    return args
  })
}

在 public/index.html 里用 EJS 语法引入:

<% for (var i in htmlWebpackPlugin.options.cdn.js) { %>
  <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
<% } %>

11.3 配置 HMR(热模块替换)和自动刷新

devServer: {
  hot: true,
  liveReload: true
}

11.4 构建不同环境的配置

publicPath: process.env.NODE_ENV === 'production'
  ? process.env.VUE_APP_PUBLIC_PATH
  : '/',
outputDir: process.env.VUE_APP_OUTPUT_DIR || 'dist'

11.5 配置静态资源目录

assetsDir: 'static'

12. 调试与排查建议

  • 配置生效检查:可在 vue.config.js 里 console.log 输出关键参数,或用 vue inspect > output.js 查看最终 webpack 配置。
  • 热更新失效:检查 devServer 的 hot 和 liveReload,以及是否有缓存未清理。
  • 代理不生效:确保前端请求路径和代理路径一致,注意 pathRewrite 设置。
  • 样式全局变量未生效:确认 loaderOptions 路径和写法无误。
  • 打包体积过大:用 webpack-bundle-analyzer 分析,排查大依赖、重复依赖,考虑使用 CDN。

13. 总结

  • vue.config.js 支持高度自定义,适用于大部分实际项目需求
  • 通过 configureWebpackchainWebpack 可定制 webpack 行为
  • devServercsspluginOptions 等覆盖开发、构建、样式、插件等方方面面
  • 多用环境变量和条件判断,让配置更灵活
  • 遇到问题时善用官方文档和社区资源
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猩火燎猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值