全局安装generator-stencil后找不到../utils/composeObjs模块的求助
I ran into a nearly identical relative path issue when testing Yeoman generators with npm link, so I know exactly what’s tripping you up here. Let’s break down why this error happens and walk through how to fix it.
Why This Error Occurs
When you use npm link to test your generator locally, Yeoman executes the generator from its globally linked system location—not your current working directory. The relative path ../utils/composeObjs in your sub-generators (like app/index.js) gets resolved relative to that global link path, not your project’s root folder. That’s why Node.js can’t locate the utils file where it expects it.
Step-by-Step Fixes
1. Use Absolute Paths with __dirname
Replace the relative require statements in your sub-generators with an absolute path built using __dirname and path.join. This guarantees the path resolves correctly no matter where the generator is run from.
For example, in app/index.js:
const path = require('path'); const composeObjs = require(path.join(__dirname, '../../utils/composeObjects'));
__dirnamerefers to the directory of the current file (e.g.,generator-stencil/app), so../../utils/composeObjectscorrectly navigates up two levels to your project’s root utils folder.
Repeat this pattern for page/index.js and component/index.js—adjust the number of ../ segments to match their depth from the project root.
2. Verify Your File Structure & Exports
Double-check your project structure matches what you expect:
generator-stencil/ ├── utils/ │ └── composeObjects.js ├── app/ │ └── index.js ├── page/ │ └── index.js ├── component/ │ └── index.js └── package.json
Also confirm composeObjects.js properly exports the composeObjs function:
// utils/composeObjects.js module.exports = function composeObjs(obj1, obj2) { // Your implementation logic here };
3. Refresh Your npm Link
Stale symlinks can cause unexpected path issues. Try unlinking and relinking your generator:
# Run from your generator's root directory npm unlink -g generator-stencil npm link
You can confirm the global link exists with:
npm ls -g generator-stencil
4. Clear npm Cache (Optional)
If you’re still hitting snags, clearing the npm cache might resolve lingering issues:
npm cache clean --force
Final Notes
Relative paths work reliably when your code runs from its original project directory, but they break when the code is symlinked globally (like with npm link). Using absolute paths with __dirname is the most robust way to avoid this problem in Yeoman generators.
内容的提问来源于stack exchange,提问作者Akash Gutha

