我很难使用带有Typescript的外部库。我非常想为没有类型可用的库添加自定义类型,而我在理解如何导入以及如何使用类型方面很费劲。
有什么区别,以及在以下情况下对应的键入如何查找:
import something = require('something');
import * as something from 'something';
const something = require('something');
import {something} from 'something';
require
是导入外部模块的“老方法”,import
语法是当前推荐的与ES6语法一致的方法。根据TypeScript中的module
配置,tsconfig.json
此语法将转换为相关的模块类型/样式。
如果您想了解TypeScript如何解析外部模块(它支持两种模式,node
并且classic
-可在tsconfig.json
as中配置moduleResolution
),请阅读以下文档:http : //www.typescriptlang.org/docs/handbook/module-resolution.html。主要区别在于如何解决非相对模块路径。
如果您想了解TypeScript如何以及在何处查找类型(类型声明),请阅读此博客文章:http : //ivanz.com/2016/06/07/how-does-typescript-discover-type-declarations -definitions-javascript /。从博客-它会:
module.d.ts
旁边module.js
输入自定义代码typings:
inpackages.json
节点模块(in node_modules
)declare module X
的文件捆绑中查找所有环境声明(语法)tsconfig.json
。这很重要,因为该文件的存在使TypeScript将所有包含的文件作为单个“项目” /“工作区”处理/// <reference path="path/to/declarations.d.ts" />
-考虑到tsconfig.json
可以使用项目文件,我不再建议这样做。您还可以输入两种类型:
外部模块分型-现场旁边的文件或节点模块的情况下对他们的路径中存在typings:
的project.json
。语法export X
没有模块声明(文件是模块!)。考虑它们被“绑定”到代码文件中,以及诸如“这是该模块的外观”之类的东西
环境类型-可以在任何地方居住。语法为declare module X
。考虑“某处存在类型/模块X,这就是它的样子”。对于模块,TypeScript将根据模块名称进行匹配。其他用例是全局变量(例如jQuery $
)。
有关如何配置以及如何配置的文档,请tsconfig.json
阅读此处:https : //github.com/Microsoft/TypeScript/wiki/tsconfig.json
关于您提供的不同示例-假设您有一个名为的模块moduleA
。要注意的一件事是,文件是JS / TS世界中的一个模块,因此:
模组
export class Car
{
public model: string = "";
}
moduleA.js-已编译(目标ES5和模块类型CommonJS)
"use strict";
var Car = (function () {
function Car() {
this.model = "";
}
return Car;
}());
exports.Car = Car;
主要
import moduleA = require("./moduleA");
new moduleA.Car();
// equivalent to the above - import everything under myModuleName
import * as myModuleName from './moduleA';
new myModuleName.Car();
// import only the Car class
import {Car} from './moduleA'
new Car();
// import only the Car class and alias it as MyCar
import {Car as MyCar} from './moduleA'
new MyCar();
main.js-已编译(目标ES5和模块类型CommonJS)
"use strict";
var moduleA = require("./moduleA");
new moduleA.Car();
// equivalent to the above - import everything under myModuleName
var myModuleName = require('./moduleA');
new myModuleName.Car();
// import only the Car class
var moduleA_1 = require('./moduleA');
new moduleA_1.Car();
// import only the Car class and alias it as MyCar
var moduleA_2 = require('./moduleA');
new moduleA_2.Car();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句