简体   繁体   English

编译器没有抛出“找不到模块”错误

[英]Compiler not throwing “Cannot find module” error

In my project I have 2 files: 在我的项目中,我有2个文件:

foo.js foo.js

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

boo.tsx 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. foo.js中, TypeScript正确地发现图像不存在并抛出“找不到模块”错误,但是没有为boo.tsx抛出错误,因此当应用程序崩溃时,错误只会出现在运行时。

If I just rename boo.tsx to boo.js TS again starts throwing the error as expected. 如果我只是将boo.tsx重命名为boo.js TS再次开始按预期抛出错误。

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 不同的模块和moduleResolution设置
  • using import instead of require 使用import而不是require
  • with and without @types/node 有和没有@types/node

Is there any special tsconfig settings I am missing or what am I doing wrong? 是否有任何特殊的tsconfig设置我缺少或我做错了什么?

The require function has no special meaning in a .ts or .tsx file, since TypeScript only uses recognizes syntax for imports. require函数在.ts.tsx文件中没有特殊含义,因为TypeScript仅使用识别语法进行导入。

In a .js file with allowJs , it is uses heuristics, and recognizes the require call as an import. 在带有allowJs.js文件中,它使用启发式方法,并将require调用识别为导入。

The more equivalent thing for TypeScript would be something like 类似于TypeScript的东西更像是

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

or one of the ES module syntaxes such as 或其中一个ES模块语法,如

import * as foo from "foo";

import foo from "foo";

尝试添加"allowSyntheticDefaultImports": true到您的tsconfig

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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