vue.config.js详解

vue.config.js 是一个可选的配置文件,如果项目的 (和 package.json 同级的) 根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载。

配置项详情见   配置参考 | Vue CLI

'use strict'
// import proxy from './proxy.config.js'
const proxy = require('./src/proxy.config.js')
const path = require('path')
const defaultSettings = require('./src/settings.js')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
// const WebpackBundleAnalyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || 'vue Element Admin' // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following method:
// port = 9527 npm run dev OR npm run dev --port = 9527
const port = process.env.port || process.env.npm_config_port || 9527 // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  // lintOnSave: process.env.VUE_APP_ENV === 'development',  // 太多警告没解决,lint会造成serve热更新时间过长
  lintOnSave: false,
  productionSourceMap: false,
  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: proxy
  },
  // configureWebpack: {
  //   plugins: [
  //     new CompressionWebpackPlugin({
  //       filename: '[path].gzip[query]',   // 提示compression-webpack-plugin@2.0.0的话filename改为asset
  //       algorithm: 'gzip',
  //       test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
  //       threshold: 10240, //内容超过10KB进行压缩
  //       minRatio: 0.8
  //     }),
  //     new BundleAnalyzerPlugin()
  //   ],
  //   name,
  //   resolve: {
  //     alias: {
  //       '@': resolve('src')
  //     }
  //   }
  // },
  configureWebpack: config => {
    return {
      // plugins: [
      //     new CompressionWebpackPlugin({
      //         // asset: '[path].gz[query]',
      //         filename: '[path].gz[query]',
      //         algorithm: 'gzip',
      //         test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
      //         threshold: 2048,
      //         minRatio: 0.8
      //     }),
      //     new WebpackBundleAnalyzer()
      // ],
      name,
      resolve: {
        alias: {
          '@': resolve('src')
        }
      },
      externals: {
        'echarts': 'echarts',
        // 'axios': 'axios',
        'vue-clipboard2': 'VueClipboard',
        'moment': 'moment'
      }
    }
  },
  transpileDependencies: [
    'hui',
    /@hui-pro/
  ],
  chainWebpack(config) {
    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/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .exclude.add(resolve('src/example'))
      .end()
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config.output.filename('[name].[hash].js').end()

    config
      // https://webpack.js.org/configuration/devtool/#development
      .when(process.env.VUE_APP_ENV === 'development',
        config => config.devtool('cheap-source-map')
      )

    config.plugin('compressionPlugin').use(new CompressionWebpackPlugin({
      test: /\.js$|\.html$|.\css/, // 匹配文件名
      threshold: 10240, // 对超过10k的数据压缩
      deleteOriginalAssets: false // 不删除源文件
    }))

    config
      .when(process.env.VUE_APP_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',
              maxSize: 1000 * 1024, // 200kb,尝试将大于200kb的文件拆分成n个200kb的文件
              // automaticNameDelimiter: '_',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                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')
        }
      )
  }
}

1.'use strict' //声明为严格模式,不能使用未声明的变量

2.const path = require("path") //引入node.js工具模块path,用来处理文件路径的小工具

3.function resolve(dir) {return path.join(__dirname, dir)}  //获取dir的绝对路径

4.const port = process.env.port || process.env.npm_config_port || 9527   //赋值port:如果当前环境端口存在则为当前环境端口,否则找process.env.npm_config_port这个属性,还没有则赋值9527

5.module.exports //commonJS的模块化 注意与ES6模块化的区别

6.publicPath: '/', //部署应用包时的基本 URL

7.outputDir: 'dist', //输出文件目录,当运行 vue-cli-service build 时生成的生产环境构建文件的目录。注意目标目录在构建之前会被清除 (构建时传入 --no-clean 可关闭该行为)。

8.assetsDir: 'static', //放置生成的静态资源 (js、css、img、fonts) 的目录。

9.lintOnSave: false, //是否在保存的时候使用 `eslint-loader` 进行检查,有效的值:`ture` | `false` | `"error"`  当设置为 `"error"` 时,检查出的错误会触发编译失败。

10.productionSourceMap: false, //如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。

11.devServer中的proxy // 代理

12.configureWebpack //webpack配置项,详情见 Working with Webpack | Vue CLI

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

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

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值