我有一个使用TypeScript的简单示例项目:https://github.com/unindented/ts-webpack-example

运行tsc -p .(tsc版本1.8.10)会引发以下问题:

app/index.ts(1,21): error TS2307: Cannot find module 'components/counter'.
components/button/index.ts(2,22): error TS2307: Cannot find module 'shared/backbone_base_view'.
components/button/index.ts(3,25): error TS2307: Cannot find module 'shared/backbone_with_default_render'.
components/counter/index.ts(2,22): error TS2307: Cannot find module 'shared/backbone_base_view'.
components/counter/index.ts(3,25): error TS2307: Cannot find module 'shared/backbone_with_default_render'.
components/counter/index.ts(4,27): error TS2307: Cannot find module 'shared/backbone_with_subviews'.
components/counter/index.ts(5,20): error TS2307: Cannot find module 'components/button'.

它抱怨所有本地文件的导入,如下所示:

import Counter from 'components/counter';

如果我将其更改为相对路径,它会起作用,但我不想这样做,因为在移动文件时,这会使我的生活更加困难:

import Counter from '../components/counter';

vscode代码库不使用相对路径,但它们的所有功能都很好,所以我的项目中肯定缺少了一些东西:https://github.com/Microsoft/vscode/blob/0e81224179fbb8f6fda18ca7362d8500a263cfef/src/vs/languages/typescript/common/typescript.ts#L7-L14

你可以查看我的GitHub repo,但如果有帮助的话,下面是我正在使用的tsconfig.json个文件:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "noImplicitAny": false,
    "removeComments": false,
    "preserveConstEnums": true,
    "sourceMap": true,
    "outDir": "dist"
  },
  "exclude": [
    "dist",
    "node_modules"
  ]
}

有趣的是,使用ts-loader通过webpack构建项目很好,所以我猜这只是一个配置问题...

推荐答案

@弗拉迪玛回复this issue on GitHub:

编译器解析模块的方式由

{
    "compilerOptions": {
        "moduleResolution": "node"
    }
}

Typescript相关问答推荐

如果我有对象的Typescript类型,如何使用其值的类型?

TS不推断类型在条件判断后具有属性'

Webpack说你可能需要在Reactjs项目中增加一个加载器''

返回同时具有固定键和变量键的对象的函数的返回类型

基于键的值的打字动态类型;种类;

TypeScrip:基于参数的条件返回类型

如何在已知基类的任何子类上使用`extends`?

如何在typescript中为this关键字设置上下文

使用TypeScrip的类型继承

如何为特定参数定义子路由?

如何通过转换器类继承使用多态将对象从一种类型转换为另一种类型

打字脚本错误:`不扩展[Type]`,而不是直接使用`[Type]`

TypeScript:如何使用泛型和子类型创建泛型默认函数?

如何在Vue动态类的上下文中解释错误TS2345?

TypeScript中的这些条件类型映射方法之间有什么区别?

如何在TypeScript中将元组与泛型一起使用?

为什么我会得到一个;并不是所有的代码路径都返回一个值0;switch 中的所有情况何时返回或抛出?(来自vsCode/TypeScript)

Karma Angular Unit测试如何创建未解析的promise并在单个测试中解决它,以判断当时的代码是否只在解决后运行

带动态键的 TS 功能

我可以在 Typescript 中重用函数声明吗?