简体   繁体   中英

Node.js cannot import from a file in the same directory

My project directory's structure is as follows:

ghostbot (main project directory)
- package.json
- package-lock.json
- src/
-- (*.ts files)
- build/
-- (compiled *.js files)
- node_modules/
- tsconfig.json

My npm start script is a simple TS compilation and starting the compiled index.js :

"scripts": {
  "start": "npx tsc --rootDir src --outDir build && node build/index.js"
},

After I run npm start from the main directory, the typescript is compiled properly (I can see files appearing in build/ ), then node starts and throws this error:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '[...]\ghostbot\build\setup' imported from [...]\ghostbot\build\index.js

Interestingly, when I look at the problematic import in the compiled index.js in WebStorm, I see this: 当我将鼠标悬停在它上面时,WebStorm 能够正确解析导入的文件。

WebStorm seems to resolve the problematic ./setup import path correctly, but Node can't.

I tried running the compilation followed by node manually, including from the build directory rather than node build/something from the main dir. I tried various formats for the import path (including the complete verbose path starting at my C: drive), always with the same error as described in the post.

I am not a TypeScript expert but I guess you should import from "setup.js" not from "setup". I think when you try to import from "setup" then node.js tries to find a module "setup" in "node_modules" directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM