简体   繁体   中英

“Cannot find module” when using tsc to compile TypeScript using esm

I have an esm package.json like so:

{
  "main": "config.js",
  "type": "module",
  "scripts": {
    "start": "npm run build && node ./build/config.js",
    "build": "tsc",
    ...

and a tsconfig.json :

{
  "compilerOptions": {
    "target": "ES2015",
    "module": "ES2020",
    "strict": true,
    "esModuleInterop": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "outDir": "./build"
  },
  "include": ["./src", "config.ts"],
  "exclude": ["./*/**.spec.js"]
}

When running npm run start I get the following error:

> tsc

internal/modules/run_main.js:54
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'F:\Development\test\example\build\src\handlers\index' imported from F:\Development\test\example\build\config.js
    at finalizeResolution (internal/modules/esm/resolve.js:277:11)
    at moduleResolve (internal/modules/esm/resolve.js:658:10)
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:748:11)
    at Loader.resolve (internal/modules/esm/loader.js:97:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:243:28)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
    at link (internal/modules/esm/module_job.js:41:36) {
  code: 'ERR_MODULE_NOT_FOUND'

The build directory looks like so:
在此处输入图像描述

I've tried already changing the type to commonjs and other configuration changes, what am I doing wrong?

Appearently even though you are using typescript, we need to change the imports to .js , so in my example:

import IndexHandler from "./src/handlers/index";
becomes:
import IndexHandler from "./src/handlers/index.js"; .

It isn't considered a bug but part of TypeScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM