7

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?

6
  • What happens if you try boo.ts? Commented Jun 16, 2018 at 23:15
  • @DevanBuggay No change :( Commented Jun 16, 2018 at 23:17
  • What happens if you try module=ES5, target=ES5 and moduleResolution="Node"? Commented Jun 20, 2018 at 11:24
  • Out of curiosity, have you declared any include and exclude of files types in tsconfig.json? If so can you check whether your project includes the .png file formats. Never mind if the setup is good. Commented Jun 22, 2018 at 7:18
  • I assume both files are at the level in same folder structure. Commented Jun 25, 2018 at 2:33

2 Answers 2

2

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

3 Comments

I don't understand why it recognizes require in JS files but not in TS files. When I try the import image = require() syntax I get an error: Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from "mod"', 'import {a} from "mod"', 'import d from "mod"', or another module format instead.
Amended my response to use ES module syntax in certain cases.
This won't help either. I've mentioned in the question that i've tried import instead of require. It will always show the module as missing unless you add a declaration for that file which in turn will make it again never show the error as with require.
0

try adding "allowSyntheticDefaultImports": true to your tsconfig

1 Comment

Nope, it was always enabled.

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.