Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • different module and moduleResolution settings
  • using import instead of require
  • with and without @types/node

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

like image 258
Petr Peller Avatar asked Jun 16 '18 23:06

Petr Peller


1 Answers

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";
like image 163
Daniel Rosenwasser Avatar answered Sep 29 '22 15:09

Daniel Rosenwasser