Tom*_*mas 29 import node.js typescript tslint
有人可以使用Typescript准确解释导出和导入在NodeJS中的工作原理吗?
我的设置是:
我正在搞乱出口/进口,而不是做一些正确的编码,它让我疯狂,并且找不到任何正确的解释它是如何工作的.
进口
你能解释一下:
var module = require ("module");
import module = require("module");
import module from "module";
import {something} from "module";
import * as module from "module";
Run Code Online (Sandbox Code Playgroud)
出口
你能解释一下吗?
export = something;
export default something;
export interface|class something;
Run Code Online (Sandbox Code Playgroud)
问题
我似乎无法找到适当的方式来进行导出与导入,所以我的IDE没有被红色覆盖并向我抛出数百个错误.
一般的问题
问题清单一直在继续,但我确定一旦上面的一些问题得到解答,我可以接受其余的问题.
谢谢你,对于这样一个普遍的问题感到抱歉,但我的沮丧程度刚刚达到顶峰......
Bru*_*der 13
同意,导入/导出语法至少有两个原因令人困惑:
var module = require ("module");
工作,但这是commonjs - >没有打字import x = require('y'
)现在在TS中被弃用了TL; DR; :使用TS 1.5中引入的'es6 style'语法
我知道TS中进口/出口的"最佳"资源就是这个
总的来说,我建议阅读这本优秀的手册,它将为您的大多数问题提供答案
从默认导出
Something
被导出为默认(单个)导出,即export default Something
在ts/es6中
使用
import Something from "module"
Run Code Online (Sandbox Code Playgroud)
您实际上可以导入具有不同名称的默认导出.import SomethingElse from 'module'
也会工作
从命名出口
Something
使用export {Something}
或export class|interface Something{}
在ts/es6中导出为"module"中的命名导出
您只想导入,使用
import {Something} from "module"
Run Code Online (Sandbox Code Playgroud)
您想要导入从命名空间下的"module"导出的所有内容 mod
import * as mod from "module
Run Code Online (Sandbox Code Playgroud)
然后用 const c:mod.Something = whatever
见import
上文
export = something
不推荐使用该表单以支持新的ES6样式语法.它主要在定义文件中找到,表示js库导出单个函数/对象的事实,例如module.exports=something
.
使用ES6样式语法并避免default
导出:它们的优点是可以使用不同的名称导入它们
import {Something as SomethingElse} from "module"
具体而言,导出需要导出的内容并专门导入
在 api.ts
export interface MyInterface {
}
export class MyClass {
}
Run Code Online (Sandbox Code Playgroud)
在 main.ts
import {MyInterface, MyClass} from './api'
Run Code Online (Sandbox Code Playgroud)
有很多好的IDE可以提供优秀的linting:VSCode,Atom Typescript和Webstorm来命名一个受欢迎的少数,前两个是免费的,第三个甚至管理你的导入.
归档时间: |
|
查看次数: |
8023 次 |
最近记录: |