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