项目子模块执行npm脚本时提示webpack未找到,该如何处理?
Great question! Let's break down what's happening and how to get your sub-module builds working smoothly with the root-installed webpack.
The Root Cause
When you run npm run build:prod (either directly in a sub-module or via a root build:all script), npm looks for the webpack command in the current directory's node_modules/.bin folder by default. Since you only installed webpack in the project root, the sub-modules don't have their own copy of webpack—hence the "command not found" error.
Required Extra Config for Sub-Module package.json (Solutions)
Here are several reliable ways to make your sub-module scripts use the root webpack:
1. Use the Relative Path to Root webpack
Update your sub-module's scripts to point directly to the root's webpack binary:
"scripts": { "build:prod": "../node_modules/.bin/webpack -p --config config/webpack.prod.js" }
Adjust the relative path (../) if your sub-module is nested deeper (e.g., ../../ for a sub-sub-module). This is the simplest, no-frills fix.
2. Use --prefix in Root Scripts (Best for Unified build:all)
If your build:all script lives in the root package.json, use the --prefix flag to run sub-module scripts while leveraging the root's node_modules:
// Root package.json "scripts": { "build:all": "npm run build:prod --prefix sub-module1 && npm run build:prod --prefix sub-module2" }
This tells npm to execute the sub-module's build:prod script but look for dependencies (like webpack) in the root directory.
3. Use npx to Target Root webpack
Modify the sub-module's script to use npx with the root directory as the prefix:
"scripts": { "build:prod": "npx --prefix ../ webpack -p --config config/webpack.prod.js" }
The --prefix ../ flag directs npx to fetch webpack from the root's node_modules instead of the sub-module's.
4. Add a Helper Tool for Scalability (Optional)
If you plan to add more sub-modules later, install npm-run-all in the root to simplify batch commands:
// Root package.json "scripts": { "build:sub1": "npm run build:prod --prefix sub-module1", "build:sub2": "npm run build:prod --prefix sub-module2", "build:all": "run-s build:sub1 build:sub2" }
This keeps your root scripts clean and makes it easy to add new sub-module build commands.
Is This Implementation Feasible?
Absolutely! Sharing a single webpack installation across sub-modules is a common, efficient engineering practice. It reduces redundant dependency bloat and lets you manage webpack's version uniformly across your entire project.
The only time this approach wouldn't work is if different sub-modules require different versions of webpack—in that case, you'd need to install webpack separately in each sub-module. But for a unified setup, this shared-root-dependency pattern is ideal.
内容的提问来源于stack exchange,提问作者Alchnemesis

