dagda1
dagda1

Reputation: 28770

running node with loader ts-node/esm.js requires imports to have the .js extension

I am trying to run node 14 with my package.json set as module:

"type": "module",

If I run this command on a typescript file:

 node --loader ts-node/esm.mjs --experimental-top-level-await ./src/scripts/ts-build.ts --trace-warnings --experimental-json-modules

and I have extensionless imports like this in a typescript file

import { logger } from './logger';

I get

ERR_MODULE_NOT_FOUND

But if I change it to

import { logger } from './logger.js';

It works.

Why is this?

Upvotes: 10

Views: 13133

Answers (2)

Changdae Park
Changdae Park

Reputation: 1079

I solved it with these experimental features on Node v14.15.0.

node --loader ts-node/esm --experimental-specifier-resolution=node your/entry.ts

But if you just want command node, ts-node or webpack serve to work with typescript entry files with import statements(such as server.ts or webpack.config.ts), you can resolve the issue by setting compilerOptions under ts-node option in your tsconfig.ts.

{
    "ts-node": {
        "compilerOptions": {
            "module": "CommonJS"
        }
    },
    "compilerOptions": {
        "target": "ES6",
        "module": "ES6",
        "moduleResolution": "Node",
        "esModuleInterop": true
    },
    "include": [
        // below entries are just examples
        "src/**/*",
        "server.ts"
        "webpack.config.ts"
    ]
}

Upvotes: 11

eol
eol

Reputation: 24555

If we take a look at the spec there's this section which states:

The current specifier resolution does not support all default behavior of the CommonJS loader. One of the behavior differences is automatic resolution of file extensions and the ability to import directories that have an index file.

There's another section which states:

A file extension must be provided when using the import keyword. Directory indexes (e.g. './startup/index.js') must also be fully specified.

So it seems that the extension is actually necessary. Howvever, there's the option --experimental-specifier-resolution which you try setting to --experimental-specifier-resolution=node.

Upvotes: 1

Related Questions