我有一个具有以下结构的项目:
project/
├── package.config
├── node_modules/
│ ├── interactjs/
│ ├── ├── index.d.ts
├── src/
│ ├── browser/
│ | ├── tsconfig.json
│ | ├── index.ts
我有以下./package.json
:
{
...
"dependencies": {
"interactjs": "1.3.4"
},
"devDependencies": {
"typescript": "3.2.2"
}
}
我的./src/browser/tsconfig.json
是:
{
"compilerOptions": {
"target": "es5",
"module": "none",
"declaration": true,
"strict": true,
"strictNullChecks": false,
"outDir": "./out"
},
"typeRoots": [
"../../node_modules",
"../../node_modules/@types",
"../definitions"
],
"include": [
"./**/*"
]
}
如您所见,我还包括文件夹definitions
,因为我想在项目的所有Typescript文件中包括一些手动定义。
以下编译失败:
const p : interact.Position = { x: 1, y: 2 };
有错误:
index.ts:9:11 - error TS2503: Cannot find namespace 'interact'.
9 const s : interact.Position = { x: 1, y: 2 };
~~~~~~~~
即使在所有定义的interact
文件node_modules/interactjs
中也没有找到 index.d.ts
。
出什么问题了?
答案 0 :(得分:2)
如果不希望使用模块分辨率,则将输入文件添加到"include"
部分中应该会为您提供所需的输出。
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "none",
"declaration": true,
"strict": true,
"strictNullChecks": false,
"outDir": "./out",
"noImplicitAny": false //<------ to ignore the errors in interactjs/index.d.ts
},
"typeRoots": [
"../../node_modules",
"../../node_modules/@types",
"../definitions"
],
"include": [
"../../node_modules/interactjs/index.d.ts", //<----- include interact in the global scope
"./**/*"
]
}
index.ts
const p : interact.Position = { x: 1, y: 2 };
const s : interact.SnapPosition = { x: 1, y: 2, range: 0 };
const listener : interact.Listener = (e: interact.InteractEvent)=>{
console.log(e);
};
interact.on("cancel", listener)
内置 index.js
"use strict";
var p = { x: 1, y: 2 };
var s = { x: 1, y: 2, range: 0 };
var listener = function (e) {
console.log(e);
};
interact.on("cancel", listener);
答案 1 :(得分:1)
您似乎在tsconfig.json中缺少行"moduleResolution":"node",
。
这是我的tsconfig.json文件之一。
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
]
}
}
答案 2 :(得分:0)
导入包Typescript(和节点)时,通过在包随附的main
文件中寻找package.json
字段来确定要从该包导入哪个文件/模块。 interactjs中的package.json
文件包括以下行:
"main": "dist/interact.js",
这意味着interactjs包中的主模块名为interact.js
,位于dist/
目录中。
如果软件包的package.json
文件未明确指定类型定义文件的位置,则Typescript将假定该类型定义文件的基本名称和位置与软件包的主模块相同。给定主模块在interactjs中的位置,Typescript将在文件dist/interact.d.ts
中查找类型定义。尝试将类型定义文件从index.d.ts
重命名为interact.d.ts
,并确保它位于dist/
目录中。
如果您要编写一个包含Typescript定义的软件包,则可以通过在types
字段中包含一个package.json
字段来明确定义文件的位置,这很有帮助,如{{3 }}