简体   繁体   中英

Webpack 5 in Ceate React App can't resolve not fully specified routes

We are developing a react library and recently noticed, that it throws an error when we want to consume it with a new (webpack 5) Create React App. It complains about this:

"BREAKING CHANGE: The request failed to resolve only because it was resolved as fully specified (probably because the origin is strict EcmaScript Module, eg a module with javascript mimetype, a '.mjs' file, or a '.js' file where the package.json contains '"type": "module"')."

I managed to fix this, by adding

{
    test: /\.m?js/,
    resolve: {
      fullySpecified: false,
    },
}

While this works fine for any applications that have access to the webpack config, we'd like to make our lib "plug&play", without any eject or additional setup. What config should we have to make the consumer's webpack resolve our not fully specified routes? Code on github

Thanks in advance

I solved this without ejecting or modifying files in node_modules. First, add craco to override the webpack config: yarn add -D @craco/craco . Next, in the root of your project (where package.json is located) create a file named craco.config.js with the following content:

module.exports = {
    webpack: {
        configure: {
            module: {
                rules: [
                    {
                        test: /\.m?js$/,
                        resolve: {
                            fullySpecified: false,
                        },
                    },
                ],
            },
        },
    },
};

This config disables the breaking change that causes this error. Then change the start/build/test commands in package.json replacing react-scripts to craco :

"scripts": {
        "start": "craco start",
        "build": "craco build",
        "test": "craco test",

Now do the usual yarn start and it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM