Razzle, IE11 and HappiJS bundling

454 Views Asked by At

I've got a server-side rendered react app which uses Razzle. I'm importing @hapi/joi since that's what I want to use for my validation both server and client side. IE11 and Edge 18 are supported browsers for my app and I've got to be able to run my app(client-side) on them.

@hapi/joi v16 is not compiled(shipped as ES6) by default which leads me to think that I have to manually compile the dependency in my project due to the support required for Edge 18 and IE11.

I am attempting to do so wit this config:

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;
  },
};

However I seem to be getting a TypeError: Cannot assign to read only property 'exports' of object when I try to run my project. I know that the error is around import and module.exports but I'm not quite seeing where I am going wrong here since I require Joi in my app.

What am I doing wrong here?

PS: Pushed this up to a repo for anyone interested in case you want to have a look and the config isn't enough context https://github.com/AntonioValerievVasilev/razzle--hapi

1

There are 1 best solutions below

1
On BEST ANSWER

The issue occurs when mixing the CommonJS module.exports with ES Modules. I found a similar issue in GitHub. You could try the solution mentioned in it: replacing all module.exports = ... to export default ....

Besides, if you use @babel/plugin-transform-runtime, it will change require to import where it isn't supposed to. It can be solved to add "sourceType": "unambiguous" in .babelrc or config.js. You could refer to the answer in this thread:

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

  "sourceType": "unambiguous"
}