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

Time:12-30

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 is able to resolve the imported file correctly when I hover over it.

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.

CodePudding user response:

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.

  • Related