Javascript 打字稿导入/作为 vs 导入/需要?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35706164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript import/as vs import/require?
提问by Adam Thompson
I am using TypeScript with Express
/Node.js
.
我正在使用带有Express
/ 的TypeScript Node.js
。
For consuming modules, the TypeScript Handbook shows the following syntax:
对于消费模块,TypeScript 手册显示了以下语法:
import express = require('express');
import express = require('express');
But also the typescript.d.ts
file shows:
但该typescript.d.ts
文件还显示:
import * as express from "express";
import * as express from "express";
I also searched the MSDN blog but could not find anything.
我还搜索了 MSDN 博客,但找不到任何内容。
Which one is more correct as of early 2016? What are the differences between the two, if any?
截至 2016 年初,哪个更正确?如果有的话,两者之间有什么区别?
Where is the best source to find information on the latest syntax to use so I can find this information in the future?
在哪里可以找到有关要使用的最新语法的信息的最佳来源,以便我将来可以找到这些信息?
回答by Ryan Cavanaugh
These are mostly equivalent, but import *
has some restrictions that import ... = require
doesn't.
这些大多是等价的,但import *
有一些import ... = require
不一样的限制。
import * as
creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or new
able - it only has properties. If you're trying to import a function or class, you should use
import * as
创建一个标识符,它是一个模块对象,重点是object。根据 ES6 规范,此对象永远不可调用或不可调用new
——它只有属性。如果你想导入一个函数或类,你应该使用
import express = require('express');
or (depending on your module loader)
或(取决于您的模块加载器)
import express from 'express';
Attempting to use import * as express
and then invoking express()
is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.
根据 ES6 规范,尝试使用import * as express
然后调用express()
总是非法的。在某些运行时+转译环境中,这可能无论如何都可以工作,但它可能会在将来的任何时候没有警告地中断,这会让您感到难过。
回答by thitemple
import * as express from "express";
This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.
这是建议的做法,因为它是自去年以来 JavaScript (ES6/2015) 的标准。
In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.
无论如何,在您的 tsconfig.json 文件中,您应该将模块选项定位到 commonjs,这是 nodejs 支持的格式。