vue-cli3搭建项目之webpack配置

一、vue.config.js文件

const path = require('path')

module.exports = {
  publicPath: './', // 基本路径
  outputDir: 'dist', // 输出文件目录
  lintOnSave: false, // eslint-loader 是否在保存的时候检查
  // see https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md
  // webpack配置
  chainWebpack: (config) => {
  },
  configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      // 为生产环境修改配置...
      config.mode = 'production'
    } else {
      // 为开发环境修改配置...
      config.mode = 'development'
    }
    Object.assign(config, {
      // 开发生产共同配置
      resolve: {
        alias: {
          '@': path.resolve(__dirname, './src'),
          '@c': path.resolve(__dirname, './src/components'),
          '@p': path.resolve(__dirname, './src/pages')
        } // 别名配置
      }
    })
  },
  productionSourceMap: false, // 生产环境是否生成 sourceMap 文件
  // css相关配置
  css: {
    extract: true, // 是否使用css分离插件 ExtractTextPlugin
    sourceMap: false, // 开启 CSS source maps?
    loaderOptions: {
      css: {}, // 这里的选项会传递给 css-loader
      postcss: {} // 这里的选项会传递给 postcss-loader
    }, // css预设器配置项 详见https://cli.vuejs.org/zh/config/#css-loaderoptions
    modules: false // 启用 CSS modules for all css / pre-processor files.
  },
  parallel: require('os').cpus().length > 1, // 是否为 Babel 或 TypeScript 使用 thread-loader。该选项在系统的 CPU 有多于一个内核时自动启用,仅作用于生产构建。
  pwa: {}, // PWA 插件相关配置 see https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa
  // webpack-dev-server 相关配置
  devServer: {
    open: process.platform === 'darwin',
    host: '0.0.0.0', // 允许外部ip访问
    port: 8022, // 端口
    https: false, // 启用https
    overlay: {
      warnings: true,
      errors: true
    }, // 错误、警告在页面弹出
    proxy: {
      '/api': {
        target: 'http://www.baidu.com/api',
        changeOrigin: true, // 允许websockets跨域
        // ws: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    } // 代理转发配置,用于调试环境
  },
  // 第三方插件配置
  pluginOptions: {}
}

二、优化打包chunk-vendors.js文件体积过大
chunk-vendors.js这个文件非常大,那是因为webpack将所有的依赖全都压缩到了这个文件里面,这时我们可以将其拆分,将所有的依赖都打包成单独的js
方案一:利用splitChunks将每个依赖包单独打包,在生产环境下配置,代码如下

configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      // 为生产环境修改配置...
      config.mode = 'production'
      // 将每个依赖包打包成单独的js文件
      let optimization = {
        runtimeChunk: 'single',
        splitChunks: {
          chunks: 'all',
          maxInitialRequests: Infinity,
          minSize: 20000, // 依赖包超过20000bit将被单独打包
          cacheGroups: {
            vendor: {
              test: /[\\/]node_modules[\\/]/,
              name (module) {
                // get the name. E.g. node_modules/packageName/not/this/part.js
                // or node_modules/packageName
                const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
                // npm package names are URL-safe, but some servers don't like @ symbols
                return `npm.${packageName.replace('@', '')}`
              }
            }
          }
        }
      }
      Object.assign(config, {
        optimization
      })
    } else {
      // 为开发环境修改配置...
      config.mode = 'development'
    }
    Object.assign(config, {
      // 开发生产共同配置
      resolve: {
        alias: {
          '@': path.resolve(__dirname, './src'),
          '@c': path.resolve(__dirname, './src/components'),
          '@p': path.resolve(__dirname, './src/pages')
        } // 别名配置
      }
    })
  }

方案二、利用DllPlugin和DllReferencePlugin将依赖包打包成外部文件在index中引入
1.在package.json中新建library,用于存储即将要打包的依赖包名和打包后的文件名

{
    ...
    "name": "demo-cli3",
  	"version": "1.0.0",
    "version_lib": "1.0.0",
    "library": {
       "lib_v1_0": [
           "jquery/dist/jquery.min.js"
        ],
        "vueBucket_v1_2": [
           "vue-router",
           "vuex"
        ]
    },
    ...
}
2.创建webpack.dll.config.js文件,代码如下
const path = require('path')
const webpack = require('webpack')
const {library} = require('./package.json')
// const assetsSubDirectory = process.env.NODE_ENV === 'production'
//   ? build.assetsSubDirectory : dev.assetsSubDirectory
let { version_lib } = require('./package.json');
version_lib = version_lib.replace(/\./g,'_');
module.exports = {
  entry: library,
  output: {
    path: path.resolve(__dirname, './libs/package/js'),
    filename: `[name].${version_lib}.dll.js`,
    library: '[name]_library'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      }
    ]
  },
  optimization:{
    minimizer:[
      new UglifyPlugin({
        uglifyOptions: {
          warnings: false,
          compress: {
            drop_console: true, // console
            drop_debugger: false,
            pure_funcs: ['console.log'] // 移除console
          }
        }
      })
    ]
  },
  plugins: [
    new webpack.optimize.ModuleConcatenationPlugin(),
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /zh-cn|en-gb/),
    new webpack.DllPlugin({
      path: path.resolve(__dirname, './libs/package/json', '[name].manifest.json'),
      name: '[name]_library',
      context: process.cwd()
    })
  ]
}

3.在vue.config.js中配置DllReferencePlugin

let { version, version_lib , openGzip,library } = require('./package.json');
...
module.exports = {
  configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      // 为生产环境修改配置...
      config.mode = 'production';
      ...
      Object.assign(config, {
        ...
        plugins:[
          ...config.plugins,
          ...Object.keys(library).map(name => {
            return new webpack.DllReferencePlugin({
              context: process.cwd(),
              manifest: require(`./libs/package/json/${name}.manifest.json`),
            })
          })
        ]
      });
      ...
    } else {
      // 为开发环境修改配置...
      config.mode = 'development';
    }
    ...
  },
}
...

4.将打包好的js自动添加进index.html中
下载add-asset-html-webpack-plugin

npm install --save-dev add-asset-html-webpack-plugin
在vue.config.js中配置add-asset-html-webpack-plugin
const webpack = require('webpack');
const path = require('path');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
...
module.exports = {
   ...
   configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      // 为生产环境修改配置...
      config.mode = 'production';
        ...
      Object.assign(config, {
        ...
        plugins:[
          ...
          new AddAssetHtmlPlugin(Object.keys(library).map(name => {
            return {
              filepath: require.resolve(path.resolve(`libs/package/js/${name}.${version_lib}.dll.js`)),
              outputPath: 'static/lib/js',
              publicPath:'./static/lib/js',
              includeSourcemap: false
            }
          })),
        ]
      });
      ...
    } else {
      // 为开发环境修改配置...
      config.mode = 'development';
    }
    ...
  },
  ...
}
Logo

前往低代码交流专区

更多推荐