【问题标题】:Compiler not throwing "Cannot find module" error编译器不抛出“找不到模块”错误
【发布时间】:2018-11-26 07:02:55
【问题描述】:

在我的项目中,我有 2 个文件:

foo.js

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

boo.tsx

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

foo.js中TypeScript正确发现图片不存在并抛出“Cannot find module”错误,但是boo.tsx没有抛出错误所以该错误仅在应用崩溃时出现在运行时。

如果我只是将 boo.tsx 重命名为 boo.js TS 再次开始按预期抛出错误。

这些是我认为可能相关的一些编译器选项:

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

我试过了:

  • 不同的模块和moduleResolution设置
  • 使用 import 而不是 require
  • 有和没有@types/node

我是否缺少任何特殊的tsconfig 设置或我做错了什么?

【问题讨论】:

  • 如果你尝试boo.ts会发生什么?
  • @DevanBuggay 没有变化:(
  • 如果你尝试 module=ES5, target=ES5 和 moduleResolution="Node" 会发生什么?
  • 出于好奇,您是否在 tsconfig.json 中声明了 files 中的任何 includeexclude 类型?如果是这样,您可以检查您的项目是否包含 .png 文件格式。没关系设置好不好。
  • 我假设这两个文件都在同一个文件夹结构中。

标签: javascript reactjs typescript react-native


【解决方案1】:

require 函数在 .ts.tsx 文件中没有特殊含义,因为 TypeScript 仅使用识别语法进行导入。

在带有allowJs.js 文件中,它使用启发式算法,并将require 调用识别为导入。

TypeScript 更等价的东西是

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

或ES模块语法之一,例如

import * as foo from "foo";

import foo from "foo";

【讨论】:

  • 我不明白为什么它在 JS 文件中识别 require 而不是在 TS 文件中。当我尝试 import image = require() 语法时,我得到一个错误: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.
  • 修改了我在某些情况下使用 ES 模块语法的回复。
  • 这也无济于事。我在问题中提到我尝试导入而不是要求。除非您为该文件添加声明,否则它将始终将模块显示为丢失,这反过来又会使其再次不再像 require 那样显示错误。
【解决方案2】:

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

【讨论】:

  • 不,它一直处于启用状态。
猜你喜欢
  • 1970-01-01
  • 2017-03-02
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 2016-01-27
  • 1970-01-01
  • 2019-01-27
  • 2019-02-21
相关资源
最近更新 更多