9

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?

2 Answers 2

10

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"
    ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

The first way you mentioned works for me, however import.meta.dirname is null
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.