Webpack "Cannot find module" for "module": "esnext"
Asked Answered
D

3

7

I have a webpack project with this in my "main.ts" module:

import {Elm} from "./MainModule";

it fails with:

TS2307: Cannot find module './MainModule'.

but when I switch my "tsconfig.json" from "module": "esnext" to "module": "commonjs", it works.

However, I need "esnext" in order to have code splitting.

Thoughts?

Descent answered 16/12, 2018 at 15:16 Comment(2)
Try setting moduleResolution to node in tsconfigBarnstorm
@samdd beautiful. Put it in an answer.Descent
B
8

I had the same issue, adding "moduleResolution": "node", to tsconfig.json seems to have fixed it.

More info on it here: https://www.typescriptlang.org/docs/handbook/module-resolution.html

Brainwashing answered 27/6, 2019 at 8:19 Comment(1)
I'm seeing this answer in a few places, but this did not solve the issue for me.Lecialecithin
A
1

When you set your type to "module" in your package.json file you enable ESM modules in your project.

{
  "type": "module"
}

But this means that Node gets strict about how it locates your import files (Module Resolution). It requires file extensions on all your import statements. If you want to import a typescript (.ts) file, and you do this

import blah from './blah.ts'; // Wrong

You will get an error because typescript inconveniently removes the .ts extension from this import statement when it compiles this file. It will compile without errors, but then fail at runtime because node needs that file extension. If you instead omit the extension and do this:

import blah from './blah'; // Wrong

Typescript will leave the extension off and compile it just fine but node will again complain at runtime. It turns out you can just import .ts files with a .js extension and Typescript will compile it and leave the extension alone.

import blah from './blah.js'; // Correct

Also try setting module and moduleResolution to "Node16"

"compilerOptions": {
  "module": "Node16",
  "moduleResolution": "Node16",
  ...
}
Ailina answered 26/1 at 3:54 Comment(0)
P
0

My answer on this other post might be relevant: https://mcmap.net/q/127702/-appending-js-extension-on-relative-import-statements-during-typescript-compilation-es6-modules

Summary: the swc compiler can add the .js extension automatically when compiling, using the resolveFully and baseurl options. After that, nodejs can run the output and resolve the import correctly.

Propraetor answered 13/6 at 16:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.