【vue3】vue.config.js打包配置(vue3 + webpack + 多环境)

丑话说在前的前言

vue3和vue2在构建项目时就体现出他们的不同。所以webpack的配置也有所不一样。
vue3构建项目命令: vue create 项目名称
vue2构建项目命令: vue init webpack 项目名称在这里插入图片描述

打包配置

在vue3中的相关配置是在vue.config.js中实现的。【官网配置参考】

gzip压缩 配置

1.安装相关插件
npm install compression-webpack-plugin

2.配置 gzip压缩

// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i
module.exports = {
// ...省略部分代码

// webpack配置
  configureWebpack: (config) => {
    /* gzip压缩 */
    const productionGzipExtensions = ['html', 'js', 'css']
    config.plugins.push(
      new CompressionWebpackPlugin({
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
        threshold: 10240, // 只有大小大于该值的资源会被处理 10240
        minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
        deleteOriginalAssets: false, // 删除原文件
      })
    )
  },
}

3.温馨提示(我踩过的坑
运行命令 npm run build 时,
出现报错 Conflict: Multiple assets emit different content to the same filename assets/js/.gz
【解决方法】属性filename: ‘[path].gz[query]’ 改为 filename: ‘[path][base].gz’,

代码压缩 配置

1.安装相关插件
npm install uglifyjs-webpack-plugin

2.配置 代码压缩

// 代码压缩
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
// ...省略部分代码

// webpack配置
  configureWebpack: (config) => {
    /* 代码压缩 */
    config.plugins.push(
      new UglifyJsPlugin({
        uglifyOptions: {
          //自动删除console
          compress: {
            //warnings: false, // 若打包错误,则注释这行
            drop_debugger: true,
            drop_console: true,
            pure_funcs: ['console.log'],
          },
        },
        sourceMap: false,
        parallel: true,
      })
    )
  },
}

图片压缩 配置

1.安装依赖:
cnpm install image-webpack-loader --save-dev

2.配置 图片压缩


module.exports = {
// ...省略部分代码

 chainWebpack: config => {
         /* 压缩图片 */
        config.module
            .rule('images')
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({ bypassOnDebug: true })
            .end()
       
    }
}

3.温馨提示(我踩过的坑
使用 npm install image-webpack-loader --save-dev 安装依赖
出现报错: Error: Cannot find module ‘gifsicle’
【解决方法】
①卸载依赖: npm uninstall image-webpack-loader
②安装cnpm:npm install cnpm -g --registry=https://registry.npm.taobao.org
③利用cnpm安装依赖: cnpm install image-webpack-loader --save-dev

多环境 配置 【官网参考】

1.在根目录创建 环境文件 .env.xxx

// 举个栗子~
// .env.prod
// 生产环境
NODE_ENV = 'production'
VUE_APP_TITLE = 'prod'
VUE_APP_API_URL = '***' // 后台地址 

2.修改 package.json 文件中的 “scripts”
“build:prod”: “vue-cli-service build --mode prod”
在这里插入图片描述
3.生产环境打包
npm run build:prod

我的 vue.config.js配置

// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i

// 代码压缩
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

module.exports = {
  publicPath: './',
  outputDir: 'dist',
  assetsDir: 'assets',
  productionSourceMap: false,
  // webpack配置
  configureWebpack: (config) => {
  if (process.env.NODE_ENV === 'production') {
      /* gzip压缩 */
      const productionGzipExtensions = ['html', 'js', 'css']
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path][base].gz',
          algorithm: 'gzip',
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 10240, // 只有大小大于该值的资源会被处理 10240
          minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
          deleteOriginalAssets: false, // 删除原文件
        })
      )
    }


    /* 代码压缩 */
    config.plugins.push(
      new UglifyJsPlugin({
        uglifyOptions: {
          //自动删除console
          compress: {
            // warnings: false, // 若打包错误,则注释这行
            drop_debugger: true,
            drop_console: true,
            pure_funcs: ['console.log'],
          },
        },
        sourceMap: false,
        parallel: true,
      })
    )
  },

  chainWebpack: (config) => {
    /* 压缩图片 */
    config.module
      .rule('images')
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({ bypassOnDebug: true })
      .end()
  },
  // css相关配置
  css: {
    // 是否将组件中的 CSS 提取至一个独立的 CSS 文件中,生产环境下是 true,开发环境下是 false
    extract: true,
    // 是否为 CSS 开启 source map。设置为 true 之后可能会影响构建的性能。
    sourceMap: false,
    // 启用 CSS modules for all css / pre-processor files.(预加载)
    // modules: false,
    // css预设器配置项
    loaderOptions: {
      // 引入全局变量样式
      sass: {
         data: `@import "@/assets/css/base.scss";`
      },
    },
  },
  // 开发环境下的 webpack-dev-server 相关配置
  devServer: {
    port: 9999,
    host: '192.168.1.202', // 本机ip地址
    https: false,
    open: true,
    proxy: {
      //目的是解决跨域,若测试环境不需要跨域,则不需要进行该配置
      '/api': {
        // 拦截以 /api 开头的url接口
        target: '***', //目标接口域名
        changeOrigin: true, //是否跨域
        ws: true, //如果要代理 websockets,配置这个参数
        secure: false, // 如果是https接口,需要配置这个参数
        // 标识替换
        // 原请求地址为 /api/getData 将'/api'替换''时,
        // 代理后的请求地址为: http://xxx.xxx.xxx/getData
        // 若替换为'/other',则代理后的请求地址为 http://xxx.xxx.xxx/other/getData
        pathRewrite: {
          // 标识替换
          '^/api': '/', //重写接口 后台接口指向不统一  所以指向所有/
        },
      },
    },
  },
}

猜你喜欢

转载自blog.csdn.net/zxsy19966/article/details/127649245