vue常用的config配置

/** 环境配置
  .env                # 在所有的环境中被载入
  .env.local          # 在所有的环境中被载入,但会被 git 忽略
  .env.[mode]         # 只在指定的模式中被载入
  .env.[mode].local   # 只在指定的模式中被载入,但会被 git 忽略
**/
const path = require('path')
const resolve = dir => path.join(__dirname, dir)
// const version = new Date().getTime();
const isProduction = process.env.NODE_ENV === 'production';
/**
 * npm install happypack --save-dev
 * 开启多线程构建
 */
const Happypack = require('happypack');
/**打包文件分析
 * npm install webpack-bundle-analyzer –save-dev
*/
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
/**打包Gzip压缩
 * npm install --save-dev compression-webpack-plugin
 * 如证书验证失败
 * npm config set strict-ssl false
 * // "compression-webpack-plugin": "^6.0.4"
*/
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg|png)(\?.*)?$/i;
/**代码压缩
 * npm i -D uglifyjs-webpack-plugin@beta
*/
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
/**引入CSDN*/
const externals = process.env.NODE_ENV == 'development' ? {} : {
  axios: 'axios',
}
/**图片压缩
 * cnpm install image-webpack-loader --save-dev
*/
/**
 * 多页面配置
 * */
let objectProject = {             // 配置多页面打包
  index: {
    entry: 'src/main.js', // 入口文件地址
  },
  pages: {
    entry: 'src/pages/main.js', // 入口文件地址
  },
}
let page = {}

let projectname = process.argv[3] // 获取build后面的参数确定执行哪个文件 例如: yarn run bulid index

if (process.env.NODE_ENV == 'development') {
  for (let a in objectProject) {
    page[a] = {
      entry: objectProject[a].entry,
      template: `public/${a}.html`,
      filename: `${a}.html`
    }
  }
} else {
  /**测试打包*/
  if (projectname == '--mode') {
    for (let a in objectProject) {
      page[a] = {
        entry: objectProject[a].entry,
        template: `public/${a}.html`,
        filename: `${a}.html`
      }
    }
  }
  /**单独模块打包*/
  else if (projectname) {
    page[projectname] = {
      entry: objectProject[projectname].entry,
      template: `public/${projectname}.html`,
      filename: `${projectname}.html`
    }
  }
  /**打包整个程序*/
  else {
    for (let a in objectProject) {
      page[a] = {
        entry: objectProject[a].entry,
        template: `public/${a}.html`,
        filename: `${a}.html`
      }
    }
  }
}

module.exports = {
  publicPath: './',
  // 生产环境是否生成 sourceMap 文件
  productionSourceMap: false,
  outputDir: projectname ? 'dist/' + projectname : 'dist',
  assetsDir: 'static',
  pages: page,
  css: {
    requireModuleExtension: true,
    extract: true, //打包时打开,不然无法热更新样式
    sourceMap: true,
    loaderOptions: {
      sass: {
        prependData: `@import "@/app.scss";`
      }
    }
  },
  configureWebpack: config => {
    config.externals = externals
    config.devtool = 'source-map'
    /**开启多线程打包*/
    config.plugins.push(
      new Happypack({
        loaders: ['babel-loader', 'vue-loader', 'url-loader'],
        cache: true,
        threads: 16 // 线程数取决于你电脑性能的好坏,好的电脑建议开更多线程
      })
    )
    if (isProduction) {
      /**代码分析*/
      config.plugins.push(
        new BundleAnalyzerPlugin(
          {
            analyzerMode: 'server',
            analyzerHost: '127.0.0.1',
            analyzerPort: 6000, // 运行后的端口号
            reportFilename: 'report.html',
            defaultSizes: 'parsed',
            openAnalyzer: true,
            generateStatsFile: false,
            statsFilename: 'stats.json',
            statsOptions: null,
            logLevel: 'info'
          }
        )
      )
      // config.output = { // 输出重构  打包编译后的 文件名称  【模块名称.版本号.时间戳】
      //   filename: `js/[name].${version}.js`,
      //   chunkFilename: `js/[name].${version}.js`
      // }
      /**GZIP压缩*/
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: productionGzipExtensions,
          threshold: 10240,//对10K以上的数据进行压缩
          minRatio: 0.8,
          deleteOriginalAssets: false,//是否删除源文件
        })
      )
      config.plugins.push(
        new UglifyJsPlugin({
          uglifyOptions: {
            compress: {
              drop_console: true,// 注释console
              drop_debugger: false, // 注释debugger
              pure_funcs: ["console.log"] //移除console
            },
            // warnings: false,
            mangle: false,
            output: {
              beautify: true //压缩注释
            }
          },
          sourceMap: false,// 去除打包后生成的.map文件
          parallel: true
        }),
      )
    }
  },
  chainWebpack: config => {
    /**别名*/
    config.resolve.alias.set("@", resolve("src"));
    if (isProduction) {
      config.plugins.delete('prefetch');
      config.plugins.delete('preload');
      /** ============压缩图片 start============ */
      config.module
        .rule('images')
        .use('image-webpack-loader')
        .loader('image-webpack-loader')
        .options({ bypassOnDebug: true })
        .end()
      /**小于10K的图片内联*/
      const imagesRule = config.module.rule('images')
      imagesRule.uses.clear()
      imagesRule
        .test(/\.(png|jpe?g|gif|svg|webp)$/i)
        .use('file-loader')
        .loader('url-loader')
        .options({
          limit: 10240,
          fallback: {
            loader: 'file-loader',
            options: {
              outputPath: 'static/images'
            }
          }
        })
        .end()
      config.optimization.minimize(true)
    }

  },
  devServer: {
    port: 8080,
    open: true,
    disableHostCheck: true,
    proxy: {
      /*线上基础配置*/
      '/dev/': {
        target: 'http://127.0.0.1/', // 这里写你自己的服务器域名
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/dev': ''
        }
      },
      /** socket = new WebSocket('ws://' + location.host + '/wss');*/
      '/wss': {
        target: 'ws://127.0.0.1:10001',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/wss': '',
        }
      },
    },
  },
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

卤鸽子

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

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

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

打赏作者

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

抵扣说明:

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

余额充值