我有一个使用Razzle的服务器端渲染的React应用。我正在导入@ hapi / joi,因为这就是我要用于服务器端和客户端的验证。 IE11和Edge 18是我的应用程序受支持的浏览器,而且我必须能够在它们上运行我的应用程序(客户端)。
@ hapi / joi v16默认情况下未编译(作为ES6提供),由于Edge 18和IE11所需的支持,我认为我必须在项目中手动编译依赖项。
我正在尝试使用此配置:
const nodeExternals = require('webpack-node-externals');
const fs = require('fs');
module.exports = {
modifyBabelOptions() {
return {
presets: ['razzle/babel'],
};
},
modify(config, { target, dev }, webpack) {
// package un-transpiled packages
const babelRuleIndex = config.module.rules.findIndex(
(rule) => rule.use && rule.use[0].loader && rule.use[0].loader.includes('babel-loader')
);
config.module.rules[babelRuleIndex] = Object.assign(config.module.rules[babelRuleIndex], {
include: [
...config.module.rules[babelRuleIndex].include,
fs.realpathSync('./node_modules/@hapi/')
],
});
config.externals =
target === 'node'
? [
nodeExternals({
whitelist: [
dev ? 'webpack/hot/poll?300' : null,
/\.(eot|woff|woff2|ttf|otf)$/,
/\.(svg|png|jpg|jpeg|gif|ico)$/,
/\.(mp4|mp3|ogg|swf|webp)$/,
/\.(css|scss|sass|sss|less)$/,
/^@hapi/,
].filter(Boolean),
}),
]
: [];
// return
return config;
},
};
但是,当我尝试运行我的项目时,我似乎得到了TypeError: Cannot assign to read only property 'exports' of object
。我知道该错误与import和module.exports有关,但是自从我在应用程序中require
Joi以来,我不太清楚这里出了什么问题。
我在这里做错了什么?
PS:如果您想看一下并且配置不够上下文,请将其推送给任何有兴趣的人https://github.com/AntonioValerievVasilev/razzle--hapi
当将CommonJS module.exports
与ES模块混合时会发生此问题。我在GitHub中找到了similar issue。您可以尝试其中提到的the solution:将所有module.exports = ...
替换为export default ...
。
此外,如果您使用@babel/plugin-transform-runtime
,它将在不应该使用的地方将require
更改为import
。可以解决的是在"sourceType": "unambiguous"
或config.js中添加.babelrc
。您可以在此线程中引用the answer:
module.exports = {
presets: [
...
],
"sourceType": "unambiguous"
}