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

2,455次阅读
没有评论

共计 1678 个字符,预计需要花费 5 分钟才能阅读完成。

提醒:本文最后更新于2025-07-07 14:44,文中所关联的信息可能已发生改变,请知悉!

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

1 编译构建时不添加 use strict

1.1 babel-loader 设置 strictMode=false

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

webpack 构建结果移除 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

正文完
 0
任侠
版权声明:本站原创文章,由 任侠 于2021-04-27发表,共计1678字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码