首页 > 解决方案 > 仅使用目录导入 index.ts

问题描述

我正在尝试从目录导入模块 index.ts 而不指定模块名称本身,而仅指定目录名称,这会导致TS2307: Cannot find module错误。

./src/main.ts:

'use strict';

// success
import {helloWorld as helloWorld1} from '../lib/helloworld/index';

// failure
import {helloWorld as helloWorld3} from '../lib/helloworld';

helloWorld1();

./lib/helloworld/index.ts:

'use strict';

export function helloWorld() {
    console.log('Hello World');
}

这在使用原生 JavaScript 时按预期工作,但在 TypeScript 中失败。我究竟做错了什么?

标签: typescript

解决方案


确保您使用的是节点路径解析策略。

在您的tsconfig.json中,将您设置compilerOptions.moduleResolution"node"


推荐阅读