0

I have a personal project using node.js, express.js and typescript.

When I run command to build project, it does all right.

But when I try to run it, it crashes, because all imports are "wrong", have a look:

The file dist/index.js has this import:

import app from './core/app';
...

BUT, if I make this change to the import, it runs ok:

import app from './core/app.js';
...

I didn't want to create a script file to do this, how can I solve it?

I'm currently using node version 16.0.

Here is my folder structure

enter image description here

Here is my index.ts

import app from 'src/core/app';

/**
 * Initializing server
 */
app.listen(app.get('port'), () => console.log('Application running -> true'));

Here is my tsconfig.json

{
    "compilerOptions": {
        "lib": ["ES2021"],
        "target": "ES2021",
        "module": "ES2020",
        "moduleResolution": "node",
        "strict": true,
        "baseUrl": ".",
        "sourceMap": true,
        "outDir": "dist",
        "rootDir": "src",
        "skipLibCheck": true,
        "noImplicitAny": true,
        "esModuleInterop": true,
        "isolatedModules": true,
        "removeComments": true,
        "resolveJsonModule": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "useUnknownInCatchVariables": true,
        "allowSyntheticDefaultImports": true,
        "strictPropertyInitialization": false,
        "forceConsistentCasingInFileNames": true,
        "typeRoots": ["node_modules/@types", "src/@types"]
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules", "dist"]
}
Henrique
  • 123
  • 1
  • 9
  • 1
    Could you try `import app from './core/app';` inside your app instead of `src/core/app`? – Webber May 10 '22 at 20:47
  • 1
    @Webber That's a known and documented behavior. TypeScript doesn't add the extension and ES6 modules don't work without extension. A relative path won't change anything. – jabaa May 10 '22 at 20:55
  • 1
    @jabaa Perhaps not, but referencing `src` as if it is a module is also not correct as far as I know. – Webber May 10 '22 at 22:04
  • 1
    @Webber It's possible. You can use an alias for a path. A convention is to prefix the alias with `@`, but it's optional. The documentation doesn't use the prefix: https://www.typescriptlang.org/tsconfig#paths You can create the alias `src` and point it to `./src`. In another question I've seen, that the OP uses aliases in their projects. In addition, the code in the question works with extension and doesn't work without extension. The absolute path doesn't seem to be a problem here. – jabaa May 10 '22 at 22:36
  • 2
    @Webber I checked my projects. In TypeScript you can use `import something from 'src/core/app`;` even without alias. TypeScript can handle it. Node.js can't handle it, but it seems like TypeScript rewrites this part of the paths or all paths are replaced by my bundler.. – jabaa May 10 '22 at 23:01

0 Answers0