Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 287
dagda1 Avatar asked Sep 09 '20 08:09

dagda1


2 Answers

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"
    ]
}
like image 148
Changdae Park Avatar answered Oct 06 '22 01:10

Changdae Park


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.

like image 35
eol Avatar answered Oct 06 '22 00:10

eol