Petr Peller
Petr Peller

Reputation: 8826

Compiler not throwing "Cannot find module" error

In my project I have 2 files:

foo.js

const image = require('../this/path/is/wrong.png');

boo.tsx

const image = require('../this/path/is/wrong.png');

In foo.js TypeScript correctly finds out that the image does not exists and throws "Cannot find module" error, but no error is thrown for boo.tsx so the bug only shows up on runtime when the app crashes.

If I just rename boo.tsx to boo.js TS again starts throwing the error as expected.

Those are some of my compiler options that I think could be relevant:

"module":"es2015",
"target": "es2015",
"jsx": "react",
"moduleResolution":"Node",
"allowJs": true,

I've tried:

Is there any special tsconfig settings I am missing or what am I doing wrong?

Upvotes: 7

Views: 219

Answers (2)

deowk
deowk

Reputation: 4318

try adding "allowSyntheticDefaultImports": true to your tsconfig

Upvotes: 0

Daniel Rosenwasser
Daniel Rosenwasser

Reputation: 23433

The require function has no special meaning in a .ts or .tsx file, since TypeScript only uses recognizes syntax for imports.

In a .js file with allowJs, it is uses heuristics, and recognizes the require call as an import.

The more equivalent thing for TypeScript would be something like

import image = require('../this/path/is/wrong.png');

or one of the ES module syntaxes such as

import * as foo from "foo";

import foo from "foo";

Upvotes: 2

Related Questions