'Building react library using Rollup, How to avoid webpack alias in next.config.js
I've setup Rollup to build a React library, when importing the library into a SPA targeting client-side rendering apps(like an app made with create-react-app) everything is okay, but when using it in a next.js app, it complains with Module not found: Can't resolve 'react' because it can't import react or react-dom and the only way to fix it now is to alias them in webpack config inside the next.js app(despite already being aliased in rollup.config.js)
I'm looking for a way to avoid this alias config in next.config.js file.
Here's my Rollup config
const config = {
input: "src/index.ts",
output: {
file: path.join(__dirname, "./dist/index.js"),
format: "es",
},
external: ['react', 'react-dom'],
plugins: [
alias({
entries: [{
find: 'react',
replacement: path.resolve(__dirname, 'node_modules/react'),
},
{
find: 'react-dom',
replacement: path.resolve(__dirname, 'node_modules/react-dom'),
}]
}),
resolve({
browser: true,
// pass custom options to the resolve plugin
moduleDirectories: ["node_modules"],
dedupe: ["react", "react-dom"],
}),
replace({
"process.env.NODE_ENV": JSON.stringify("production"),
preventAssignment: true,
}),
commonJS(),
],
};
export default config;
and here's how to solve the issue when importing the library in a next.js app
// next.config.js
const path = require('path');
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
webpack(config) {
config.resolve.alias = {
...config.resolve.alias,
'react': path.resolve(__dirname, './node_modules/react'),
'react-dom': path.resolve(__dirname, './node_modules/react-dom')
}
return config;
}
}
module.exports = nextConfig
The full code that's needed to reproduce the issue: https://github.com/lalosh/rollup-webpack-alias-issue
Solution 1:[1]
I was able to successfully run the react-library-test-app from your example repository. Assuming you already have the react-library built with Rollup, go through the following steps.
#1 - Add @lalosh/rollup-webpack-alias-issue to the dependencies of react-library-test-app.
"dependencies": {
"@lalosh/rollup-webpack-alias-issue": "1.0.0",
"next": "12.1.0",
"react": "17.0.2",
"react-dom": "17.0.2"
}
#2 - npm link @lalosh/rollup-webpack-alias-issue
From the react-library folder run the following command:
npm link
Then from the react-library-test-app folder run:
npm link @lalosh/rollup-webpack-alias-issue
#3 - Remove webpack configuration
Finally, remove the extra webpack configuration in next.config.js.
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
};
module.exports = nextConfig;
Then run the app in development mode with npm run dev. The app should be able to run without any errors.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | juliomalves |
