我有一个项目,它有这样的结构:
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 };
~~~~~~~~即使在node_modules/interactjs文件中,index.d.ts与所有定义一起存在,也找不到interact。
有什么问题吗?
发布于 2018-12-27 09:08:12
如果您希望保持模块解析为none,那么将输入文件添加到"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);发布于 2018-12-27 06:59:01
看起来您的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"
]
}
}发布于 2018-12-27 07:07:31
当您导入包时,Typescript (和Node)通过查找包中包含的package.json文件中的main字段来确定要从该包中导入哪个文件/模块。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定义的包,则通过在package.json字段中包含publishing guide中所述的types字段来明确定义文件的位置是很有帮助的
https://stackoverflow.com/questions/53937924
复制相似问题