[英]Importing typescript from external node modules
我想将我的应用程序拆分为不同的节点模块,并有一个主模块,它也构建所有其他模块,我想使用带有es6模块的typescript。
这是我计划的项目结构:
我希望能够在框架中定义可以在dep-a,dep-b和main中使用的接口。
如何正确设置? 我可以从主模块编译所有内容吗? 我是否需要为framework,dep-a,...和另一个打字文件创建不同的包? 对此最好的方法是什么?
我已经设置了一些测试文件和文件夹,并使用npm链接链接依赖项和webpack来捆绑文件,我总是遇到文件未找到的问题:
error TS2307: Cannot find module 'framework/interfaces/IComponent'
和
Module not found: Error: Cannot resolve 'file' or 'directory' ./components/test
TL; DR使用declaration: true
生成模块的declaration: true
在tsconfig.json
为declaration: true
,并在package.json
文件的typings
条目中指定生成的tsconfig.json
的文件
使用类似于这样的tsconfig
文件:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"noImplicitAny": true,
"removeComments": true,
"outDir": "dist",
...
},
"files": [
...
]
}
重要的是declaration: true
,它将在dist目录中生成内部声明
假设有一个index.ts
文件(重新)导出framework
所有有趣部分,创建一个package.json
文件,其中main
和typings
条目分别指向生成的js和生成的声明,即
{
"name": "framework",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
...
}
将此模块提交给git repo,比如bitbucket:“ https://myUser@bitbucket.org/myUser/framework.git ”
在package.json
创建对framework
的依赖
{
"dependencies": {
"framework": "https://myUser@bitbucket.org/myUser/framework.git"
},
}
这就对了。
import * from 'framework'
将自动拉出与打字的依赖关系
显然,可以使用dep-a对框架所做的事情,即生成声明,更新package.json,并使用dep-a作为主要内嵌类型的模块
注意:如果您不想通过外部git repo访问,则文件URL将在package.json / dependencies中执行
TypeScript 1.6中的内容是package.json
模块中的typings
属性。 您可以在GitHub上查看相关问题 。
因此,假设您要创建单独的模块(dep-a,框架)。 您可以执行以下操作:
main.ts // (1)
package.json // (2)
node_modules/
dep_a/
index.js // (3)
index.d.ts // (4)
package.json // (5)
node_modules/
framework/
index.js // (6)
index.d.ts // (7)
package.json // (8)
那么让我们看看你的文件中有什么:
//(1) main.ts
import * as depA from "depA";
console.log(depA({ a : true, b : 2 }) === true) // true;
//(2) package.json
{
name: "main",
dependencies: {
"dep_a" : "0.0.1"
}
...
}
对于depA
//(3) dep_a/index.js
module.exports = function a(options) { return true; };
//(4) dep_a/index.d.ts;
import * as framework from "framework";
export interface IDepA extends framework.IFramework {
a : boolean
}
export default function a(options: IDepA) : boolean;
//(5) dep_a/package.json
{
name: "dep_a",
dependencies: {
"framework" : "0.0.1"
},
...
typings : "index.d.ts" // < Magic happens here
}
对于framework
//(6) dep_a/node_modules/framework/index.js
module.exports = true // we need index.js here, but we will only use definition file
//(7) dep_a/node_modules/framework/index.d.ts;
export interface IFramework {
b : number;
}
//(8) dep_a/node_modules/framework/package.json
{
name: "framework"
...
typings : "index.d.ts"
}
我在这个答案中没有包含(为了清楚起见)是另一个编译阶段,所以你实际上可以用dep_a
编写模块( dep_a
, framework
),然后在使用它们之前将它们编译成index.js
。
有关详细说明和一些背景信息,请参阅: https : //medium.com/@mweststrate/how-to-create-strongly-typed-npm-modules-1e1bda23a7f4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.