在使用 Webpack 进行前端开发时,经常会遇到 "TypeError: Cannot assign to read only property ‘exports’ of object" 的报错。这个错误通常出现在使用 ES6 模块语法时,其中涉及到的模块使用了 CommonJS 规范。
错误原因
这个错误的原因是由于 ES6 模块和 CommonJS 规范在导出模块时使用的方式不同。ES6 模块使用的是静态导入和导出,而 CommonJS 规范使用的是动态导入和导出。
在 Webpack 中,当使用 ES6 模块语法时,Webpack 会将其转换为 CommonJS 规范的模块。但是,当转换后的模块被 CommonJS 规范的模块所引用时,就会出现 "TypeError: Cannot assign to read only property ‘exports’ of object" 的报错。
解决方法
解决这个问题有两种方法。
方法一:使用 Babel 转换 ES6 模块
第一种方法是使用 Babel 将 ES6 模块转换为 CommonJS 规范的模块。这个方法需要安装 Babel 和相关的插件。
首先,安装 Babel 和相关的插件:
npm install --save-dev @babel/core @babel/preset-env babel-loader
然后,在 Webpack 的配置文件中添加以下配置:
// www.javascriptcn.com code example
module.exports = {
// ...
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
};这个配置将会使用 Babel 对所有的 JavaScript 文件进行转换,将 ES6 模块转换为 CommonJS 规范的模块。
方法二:使用 Webpack 的 resolve.mainFields 配置
第二种方法是使用 Webpack 的 resolve.mainFields 配置,将模块的导出方式设置为 "module"。
在 Webpack 的配置文件中添加以下配置:
module.exports = {
// ...
resolve: {
mainFields: ['module', 'main']
}
};这个配置将会优先使用 "module" 导出方式,如果没有找到 "module" 导出方式,则使用 "main" 导出方式。
示例代码
下面是一个使用 ES6 模块语法并且出现 "TypeError: Cannot assign to read only property ‘exports’ of object" 的示例代码:
// www.javascriptcn.com code example
// moduleA.js
export const a = 1;
// moduleB.js
import { a } from './moduleA';
module.exports = { a };
// index.js
const { a } = require('./moduleB');
console.log(a);在这个示例代码中,moduleA.js 使用了 ES6 模块语法导出了一个常量 a;moduleB.js 使用了 CommonJS 规范导出了一个对象,其中包含了 a;index.js 使用了 CommonJS 规范导入了 moduleB.js 中的对象,并打印了 a。
当运行 index.js 时,就会出现 "TypeError: Cannot assign to read only property ‘exports’ of object" 的报错。
使用方法一或方法二中的任意一种方法都可以解决这个报错。下面是使用方法一的示例代码:
// www.javascriptcn.com code example
// .babelrc
{
"presets": ["@babel/preset-env"]
}
// webpack.config.js
module.exports = {
// ...
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
}
};
// index.js
import { a } from './moduleB';
console.log(a);在这个示例代码中,添加了 .babelrc 文件,并配置了 @babel/preset-env 插件;修改了 Webpack 的配置文件,将 Babel 添加到了 JavaScript 文件的转换流程中;修改了 index.js 文件,使用 ES6 模块语法导入了 a,并打印了 a。
运行 index.js 时,就不会再出现 "TypeError: Cannot assign to read only property ‘exports’ of object" 的报错。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d2319ba941bf713442ccf2