使用Create React App+Yarn Workspaces多模块项目依赖问题求助
我之前也碰到过类似的多模块项目依赖打包坑,结合你的场景,给你几个可行的解决思路:
问题根源
你的other-lib-project编译后用require("faker")引入依赖,但Create React App(CRA)默认的Webpack配置不会自动打包workspace子库的依赖——因为Yarn Workspaces会把依赖提升到根目录,而CRA的打包逻辑默认认为这些依赖应该由主项目管理,导致运行时浏览器中找不到faker模块,所以才会出现Cannot read property 'random' of undefined的错误。
方案1:将依赖打包进库文件(适合库需要独立分发的场景)
如果你的other-lib-project需要作为独立库使用,或者不想让主项目管理它的依赖,可以修改库的编译配置,把faker直接打包进输出文件:
调整TypeScript配置:
在other-lib-project/tsconfig.json中确保以下核心配置:{ "compilerOptions": { "module": "ESNext", "target": "ES6", "declaration": true, "outDir": "./dist" } }用Rollup单独编译库:
先安装必要插件:yarn add rollup rollup-plugin-typescript2 rollup-plugin-node-resolve rollup-plugin-commonjs --dev然后创建
rollup.config.js:import typescript from 'rollup-plugin-typescript2'; import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; export default { input: 'src/index.ts', output: [ { file: 'dist/index.js', format: 'umd', name: 'OtherLib', // 浏览器环境可用的全局变量名 }, { file: 'dist/index.esm.js', format: 'esm', }, ], plugins: [ typescript(), resolve({ browser: true }), // 解析适配浏览器的依赖版本 commonjs(), // 把CommonJS格式的faker转成ES模块 ], };修改库的
package.json脚本:"scripts": { "build": "rollup -c" }重新编译后,
dist目录的文件会包含faker的代码,运行时就不会缺失依赖了。
方案2:将依赖设为Peer Dependency(适合库仅在当前CRA项目使用的场景)
如果你的库只服务于当前的CRA项目,可以把faker设为peer依赖,让主项目负责安装和打包:
修改库的package.json:
把faker从dependencies移到peerDependencies:{ "peerDependencies": { "faker": "^5.5.3" // 替换成你实际使用的版本 } }安装依赖:
在项目根目录运行:yarn installYarn会自动在
create-react-app-project中安装faker作为依赖。
这样CRA的Webpack会把faker打包进主项目的bundle,运行时就能正常访问faker.random了。
方案3:修改CRA的Webpack配置(不改动库的情况下)
如果你不想调整库的配置,可以用craco修改CRA的Webpack配置,让它强制打包库的依赖:
安装craco:
yarn add @craco/craco --dev创建craco.config.js:
在create-react-app-project目录下创建配置文件:module.exports = { webpack: { configure: (webpackConfig) => { // 移除对other-lib-project的externals限制,让Webpack打包它的依赖 webpackConfig.externals = webpackConfig.externals.filter( external => !external.includes('other-lib-project') ); return webpackConfig; }, }, };替换主项目的启动脚本:
在create-react-app-project/package.json中修改脚本:"scripts": { "start": "craco start", "build": "craco build", "test": "craco test" }重启项目后,Webpack会把
other-lib-project的依赖一起打包进主项目。
额外注意点
确保根目录的package.json正确配置Yarn Workspaces:
{ "private": true, "workspaces": [ "packages/*" ] }
内容的提问来源于stack exchange,提问作者jclyons52

