使用Rollup构建react库,如何避免next.config.js中的webpack别名



我已经设置了Rollup来构建React库,当将库导入到以客户端渲染应用程序为目标的SPA中时(比如用create-rect应用程序制作的应用程序(,一切都可以,但当在next.js应用程序中使用它时,它向Module not found: Can't resolve 'react'抱怨,因为它无法导入reactreact-dom,现在唯一的解决方法是在next.js应用程序内的webpack配置中对它们进行别名(尽管已经在rollup.config.js中进行了别名(

我正在寻找一种方法来避免next.config.js文件中的alias配置。

这是我的汇总配置

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;

以下是在next.js应用中导入库时如何解决问题

// 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

重现问题所需的完整代码:https://github.com/lalosh/rollup-webpack-alias-issue

我能够从您的示例存储库成功运行react-library-test-app。假设您已经使用Rollup构建了react-library,请执行以下步骤。

#1-将@lalosh/rollup-webpack-alias-issue添加到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链路@lalosh/rollup-webpack-alias-issue

react-library文件夹运行以下命令:

npm link

然后从react-library-test-app文件夹运行:

npm link @lalosh/rollup-webpack-alias-issue
#3-删除webpack配置

最后,删除next.config.js中额外的webpack配置。

/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
};
module.exports = nextConfig;

然后使用npm run dev以开发模式运行应用程序。该应用程序应该能够在没有任何错误的情况下运行。

最新更新