webpack 构建结果移除 use strict 严格模式

目录
[隐藏]

在一些特殊需求中,需要使用到严格模式下被禁止而导致报错的语法,此时需要避免构建的结果包含 use strict

1 编译构建时不添加 use strict

1.1 babel-loader 设置 strictMode=false

babel-loader 通过 @babel/helper-module-transforms 处理模块的转换,它提供一个配置参数 strictMode 用于指定是否编译为严格模式,该参数默认为 true,也就是默认会添加 use strict。如下图所示。

通过在 babel 的配置项中明确指定该参数值为 false 可阻止该行为。示例:

{
    loader: 'babel-loader',
    options: {
        cacheDirectory: !config.nocache,
        presets: ['@babel/preset-env', { modules: 'commonjs' }],
        plugins: [
            [
                '@babel/plugin-transform-modules-commonjs',
                {
                    loose: true,
                    strictMode: false,
                },
            ],
        ]
    },
},

相关参考:

  • https://babel.dev/docs/en/babel-plugin-transform-strict-mode
  • https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs

1.2 TypeScript 编译选项设置 noImplicitUseStrict

除了 babel 外,TypeScript 默认也会开启严格模式,它的配置参数为 noImplicitUseStrict。在 tsconfig.json 文件的编译选项中设置该参数值为 true 即可关闭该功能。示例:

{
    "ts-node": {
        "transpileOnly": true
    },
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitUseStrict": true
    }
}

相关参考:

  • https://www.tslang.cn/docs/handbook/compiler-options.html

2 移除已经存在的 use strict

编译配置只能指定 babel-loaderts-loader 的输出内容不新增 use strict,但不能解决依赖文件中已经存在的情况。另外 webpack 内部也存在对于 ESmodule 引用方式添加 use strict 的逻辑,要移除它没有那么容易。

但是我们可以通过编写一个 webpackloaderplugin 方式进行移除。示例:

// stripStrictLoader.js
function StripStrictLoader(content) {
    if (content.includes('use strict')) content.replace(/('|")use strict('|");?/gm, '');
    if (this.cacheable) this.cacheable(true);
    return content;
}

module.exports = StripStrictLoader;

// webpack.config.js
module.exports = {
    module: {
        rules: [
            {
                test: /\.(t|j)sx?$/,
                enforce: 'post',
                use: [{ loader: path.resolve('./stripStrictLoader.js') }],
            }
        ]
    },
}

3 相关参考

  • https://babel.dev/docs/en/babel-plugin-transform-strict-mode
  • https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs
  • https://www.tslang.cn/docs/handbook/compiler-options.html
  • https://juejin.cn/post/6844903894057762830
点赞 (2)

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code