首页 > 解决方案 > Razzle、IE11 和 HappiJS 捆绑

问题描述

我有一个使用 Razzle 的服务器端渲染反应应用程序。我正在导入@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 ,请将其推送到任何有兴趣的人的回购

标签: reactjsinternet-explorer-11babeljsmicrosoft-edgerazzle

解决方案


将 CommonJSmodule.exports与 ES 模块混合时会出现此问题。我在 GitHub 中发现了类似的问题。您可以尝试其中提到的解决方案module.exports = ...:全部替换为export default ....

此外,如果您使用@babel/plugin-transform-runtime,它将更改requireimport不应该的位置。可以通过add "sourceType": "unambiguous"in.babelrc或者config.js来解决。你可以参考这个帖子中的答案:

module.exports = {
  presets: [
    ...
  ],

  "sourceType": "unambiguous"
}

推荐阅读