当前位置: 代码网 > it编程>前端脚本>Vue.js > vue.config.js中配置configureWebpack和chainWebpack以及一些常用的配置

vue.config.js中配置configureWebpack和chainWebpack以及一些常用的配置

2024年10月27日 Vue.js 我要评论
configurewebpack介绍configurewebpack 允许你在 vue cli 项目中直接修改 webpack 的配置。它可以通过一个对象或一个函数来实现。如果你使用的是一个函数,那么

configurewebpack

介绍

configurewebpack 允许你在 vue cli 项目中直接修改 webpack 的配置。

它可以通过一个对象或一个函数来实现。

如果你使用的是一个函数,那么它会接收默认的 webpack 配置作为参数,并且你应该返回一个修改过的配置对象。

用法

configurewebpack 可以是一个对象或一个函数:

作为对象:

  • 如果 configurewebpack 是一个对象,那么这个对象将会通过 webpack-merge 合并到最终的 webpack 配置中。
  • 这种方式适合简单的配置修改。

作为函数:

  • 如果 configurewebpack 是一个函数,那么它会接收默认的 webpack 配置作为参数。
  • 函数可以修改配置并不返回任何东西,也可以返回一个被克隆或修改过的配置版本。
  • 这种方式适合更复杂的配置修改,特别是当你需要基于环境变量或其他条件动态修改配置时。

常见配置示例

添加别名

const path = require("path");
module.exports = {
  configurewebpack: {
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src')
      }
    }
  }
};

修改输出文件名

module.exports = {
  configurewebpack: {
    output: {
      filename: '[name].[contenthash].js',
      chunkfilename: '[name].[contenthash].chunk.js'
    }
  }
};

添加 webpack 插件

module.exports = {
  configurewebpack: (config) => {
    config.plugins.push(
      new htmlwebpackplugin({
        template: './public/index.html',
        filename: 'index.html',
      })
    );
  },
};

添加额外的 loader

module.exports = {
  configurewebpack: {
    module: {
      rules: [
        {
          test: /\.md$/,
          use: [
            'vue-loader',
            {
              loader: 'markdown-loader',
              options: {
                // markdown-loader 的选项
              }
            }
          ]
        }
      ]
    }
  }
};

修改性能提示

module.exports = {
  configurewebpack: (config) => {
    config.performance = {
      hints: false, // 关闭性能提示
      maxentrypointsize: 500000,
      maxassetsize: 300000,
    };
  },
};

修改优化选项

module.exports = {
  configurewebpack: (config) => {
    optimization: {
      minimizer: [
        new terserplugin({
          terseroptions: {
            compress: {
              drop_console: true, // 去除 console
              drop_debugger: true, // 去除 debugger
            },
          },
        }),
      ],
    },
  },
};

示例

对象形式:

const path = require("path");
const terserplugin = require("terser-webpack-plugin");
const webpackobfuscator = require('webpack-obfuscator');

function resolve(dir) {
  return path.join(__dirname, dir);
}
const name = '浏览器网页标题';
module.exports = {
  configurewebpack: (process.env.node_env === 'production') ? {
    name: name,
    plugins: [
      new webpackobfuscator({ // js 混淆配置
        controlflowflattening: false,
        deadcodeinjection: false,
        ignoreimports: true, // 这里设置为true
        stringarraythreshold: 0.3,
        //  压缩代码
        compact: true,
        // 是否启用控制流扁平化(降低1.5倍的运行速度)
        controlflowflattening: false,
        // 随机的死代码块(增加了混淆代码的大小)
        deadcodeinjection: false,
        // 此选项几乎不可能使用开发者工具的控制台选项卡
        debugprotection: false,
        // 如果选中,则会在“控制台”选项卡上使用间隔强制调试模式,从而更难使用“开发人员工具”的其他功能。
        debugprotectioninterval: false,
        // 通过用空函数替换它们来禁用console.log,console.info,console.error和console.warn。这使得调试器的使用更加困难。
        disableconsoleoutput: true,
        // 标识符的混淆方式 hexadecimal(十六进制) mangled(短标识符)
        identifiernamesgenerator: 'hexadecimal',
        log: false,
        // 是否启用全局变量和函数名称的混淆
        renameglobals: false,
        // 通过固定和随机(在代码混淆时生成)的位置移动数组。这使得将删除的字符串的顺序与其原始位置相匹配变得更加困难。如果原始源代码不小,建议使用此选项,因为辅助函数可以引起注意。
        rotatestringarray: true,
        // 混淆后的代码,不能使用代码美化,同时需要配置 cpmpat:true;
        selfdefending: true,
        // 删除字符串文字并将它们放在一个特殊的数组中
        stringarray: true,
        rotateunicodearray: true,
        //  stringarrayencoding: 'base64',
        stringarrayencoding: ['base64'],
        stringarraythreshold: 0.75,
        // 允许启用/禁用字符串转换为unicode转义序列。unicode转义序列大大增加了代码大小,并且可以轻松地将字符串恢复为原始视图。建议仅对小型源代码启用此选项。
        unicodeescapesequence: false,
        // 允许启用/禁用字符串转换为unicode转义序列。unicode转义序列大大增加了代码大小,并且可以轻松地将字符串恢复为原始视图。建议仅对小型源代码启用此选项。
        transformobjectkeys: true,
      }, []),
    ],
    devtool: process.env.node_env === "production" ? "false" : "source-map",
    resolve: {
      alias: {
        "@": resolve("src"), // 添加别名 @
        'vue': path.resolve(__dirname, './', 'node_modules', 'vue') // 去重vue包,多个vue包会导致element-ui 里的 table 组件不生效
      },
    },
    // 打包生产环境时过滤console.log打印日志
    optimization: {
      minimizer: [
        new terserplugin({
          terseroptions: {
            compress: {
              drop_console: true, // 去除 console
              drop_debugger: true, // 去除 debugger
            },
          },
        }),
      ],
    },
  } : {},
}

函数形式:

const path = require("path");
const terserplugin = require("terser-webpack-plugin");
const webpackobfuscator = require('webpack-obfuscator');

function resolve(dir) {
  return path.join(__dirname, dir);
}
const name = '浏览器网页标题';
module.exports = {
	configurewebpack: (config) => {
	    config.name = name,
	      config.resolve = {
	        ...config.resolve,
	        alias: {
	          "@": resolve("src"), // 配置别名 @
	          'vue': path.resolve(__dirname, './', 'node_modules', 'vue') // 去重vue包,多个vue包会导致element-ui 里的 table 组件不生效
	        }
	      },
	      config.optimization = {
	        ...config.minimizer,
	        minimizer: [
	          new terserplugin({
	            terseroptions: {
	              compress: {
	                drop_console: true, // 去除 console.log
	                drop_debugger: true, // 去除 debugger
	              },
	            },
	          }),
	        ]
	      }
	
	    if (process.env.node_env === 'production') {
	      config.plugins.push(
	        new webpackobfuscator({
	          // 压缩代码
	          compact: true,
	          // 是否启用控制流扁平化(降低1.5倍的运行速度)
	          controlflowflattening: false,
	          // 随机的死代码块(增加了混淆代码的大小)
	          deadcodeinjection: false,
	          // 此选项几乎不可能使用开发者工具的控制台选项卡
	          debugprotection: false,
	          // 如果选中,则会在“控制台”选项卡上使用间隔强制调试模式,从而更难使用“开发人员工具”的其他功能。
	          debugprotectioninterval: false,
	          // 通过用空函数替换它们来禁用console.log,console.info,console.error和console.warn。这使得调试器的使用更加困难。
	          disableconsoleoutput: true,
	          // 标识符的混淆方式 hexadecimal(十六进制) mangled(短标识符)
	          identifiernamesgenerator: 'hexadecimal',
	          log: false,
	          // 是否启用全局变量和函数名称的混淆
	          renameglobals: false,
	          // 通过固定和随机(在代码混淆时生成)的位置移动数组。这使得将删除的字符串的顺序与其原始位置相匹配变得更加困难。如果原始源代码不小,建议使用此选项,因为辅助函数可以引起注意。
	          rotatestringarray: true,
	          // 混淆后的代码,不能使用代码美化,同时需要配置 cpmpat:true;
	          selfdefending: true,
	          // 删除字符串文字并将它们放在一个特殊的数组中
	          stringarray: true,
	          rotateunicodearray: true,
	          //  stringarrayencoding: 'base64',
	          stringarrayencoding: ['base64'],
	          stringarraythreshold: 0.75,
	          // 允许启用/禁用字符串转换为unicode转义序列。unicode转义序列大大增加了代码大小,并且可以轻松地将字符串恢复为原始视图。建议仅对小型源代码启用此选项。
	          unicodeescapesequence: false,
	          // 允许启用/禁用字符串转换为unicode转义序列。unicode转义序列大大增加了代码大小,并且可以轻松地将字符串恢复为原始视图。建议仅对小型源代码启用此选项。
	          transformobjectkeys: true,
	        })
	      )
	    }
	},
}

js 混淆参考文档:

chainwebpack

介绍

chainwebpack 是 vue cli 提供的一种更强大的方式来修改 webpack 的配置。

configurewebpack 不同,chainwebpack 使用 webpack chain api,它允许你以一种声明式的方式来修改 webpack 配置

用法

chainwebpack 接收一个函数,该函数接收一个基于 webpack chain api 的链对象作为参数。

你可以使用这个链对象来修改 webpack 的配置

常用配置示例

修改 html 插件的选项

config.plugin('html').tap(args => {
  args[0].title = 'my app';
  return args;
});

** 修改模块规则**

config.module
  .rule('images')
  .test(/\.(png|jpe?g|gif|webp)(\?.*)?$/)
  .use('url-loader')
  .loader('url-loader')
  .options({
    limit: 10000,
    name: 'img/[name].[hash:7].[ext]'
  });

去除 debugger 语句

config.when(process.env.node_env === 'production', config => {
  config.optimization.minimize(true);
  config.optimization.minimizer('terser').tap(args => {
    args[0].terseroptions.compress.drop_debugger = true;
    return args;
  });
});

注意事项

  • 使用 chainwebpack 时,请确保你了解 webpack chain api 的使用方法。
  • chainwebpack 和 configurewebpack 可以同时使用,它们会按照顺序依次应用。
  • 如果你需要对 webpack 的配置进行更复杂的操作,chainwebpack 提供了更强大的 api 来修改配置。

详细示例

const path = require("path");
module.exports = {
  chainwebpack: (config) => {
    // 修改 html 插件的选项
    config.plugin('html').tap(args => {
      args[0].title = 'my app';
      return args;
    });

    // 修改模块规则
    config.module
      .rule('images')
      .test(/\.(png|jpe?g|gif|webp)(\?.*)?$/)
      .use('url-loader')
      .loader('url-loader')
      .options({
        limit: 10000,
        name: 'img/[name].[hash:7].[ext]'
      });

    // 去除 debugger
    config.when(process.env.node_env === 'production', config => {
      config.optimization.minimize(true);
      config.optimization.minimizer('terser').tap(args => {
        args[0].terseroptions.compress.drop_debugger = true;
        return args;
      });
    });

    // 添加别名
    config.resolve.alias
      .set('@components', resolve('src/components'))
      .set('@assets', resolve('src/assets'));

    // 添加额外的插件
    config.plugin('define').tap(args => {
      args[0]['process.env'].vue_app_version = json.stringify(process.env.vue_app_version || '');
      return args;
    });

    // 修改输出选项
    config.output.filename('[name].[contenthash].js');
  },
};

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com