解决浏览器 require is not defined 的报错问题

原因

在node环境中引入了一些包,用webpack打包后放在浏览器环境中,浏览器报错require is not defined

这是因为require是node环境下的CommonJs,而import是浏览器环境下的ESModule。ESModule不认识require。
require是node的一个私有的全局方法。

解决方法

那就让打包出来的代码别有require,换句话说,webpack应该打包出一个适用于ES6环境下的代码。

只需在webpack.config.js中,将原来的target: 'node'改成target: 'web'即可。
webpack.config.js

热知识

export / export default + import ===》 ES6
module.exports / exports + require ===》CommonJS

猜你喜欢

转载自blog.csdn.net/weixin_42280517/article/details/127241185