Bundling node_modules in server.js with razzle 4.x and webpack 5.x

524 Views Asked by At

I have a Razzle application which I've recently updated from Razzle 3.3 to 4.2. In doing so I've updated a lot of packages in my package.json, including webpack.

For my Razzle 3.3 implementation I bundled the node_modules with my server.js by having the following in my razzle.config.js.

module.exports = {
    modify: (config, { target }, webpack) => {
        const appConfig = { ...config };

        if (target === 'node') {
            // some changes to appConfig

            appConfig.externals = []; // this resulted in node_modules to be bundled with my server.js
        }
    }
};

However with the update to Razzle 4.2 this no longer works. I've Googled around for quite some time unable to find any knowledge of how this is done with Razzle 4, but there are a lot of posts pointing towards this being a babel-loader issue, which I assume is possible to fix with an update to my config. On the Razzle documentation there is a section about 'Transpilation of External modules' however I assume from the example, that this is for single modules, and not the entire node_modules library.

Whenever I try to run my application in my CI environment I get the following error:

Error: Cannot find module 'react'

I can solve this error if I copy my node_modules folder to the build, however this is not an option for me, and I want the node_modules to be bundled with my application.

I was wondering if someone out there knows how this is achieved for Razzle 4.x/Webpack 5.x, whichever is the culprit?

1

There are 1 best solutions below

0
On BEST ANSWER

Updating the configuration was my solution.

When Razzle was updated to version 3.3 they deprecated the old modify function in the razzle.config.js. They replaced it by a new method, known as modifyWebpackConfig for writing the razzle config.

So I could change my code to

module.exports = {
    modifyWebpackConfig: ({ env: { target }, webpackConfig, webpackObject }) => {
        const appConfig = { ...webpackConfig };

        if (target === 'node') {
            // some changes to appConfig

            appConfig.externals = [];
        }
    
        return appConfig;
    }
}