不应该
import * as convict from "convict";
const config = convict({ ... });
// Perform validation
config.validate({ "allowed": "strict" });
export = config;
在功能上等同于:
import * as convict from "convict";
export const config = convict({ ... });
// Perform validation
config.validate({ "allowed": "strict" });
第一个代码片段有效,但第二个代码片段引入了类型错误,例如:
TypeError: config.get is not a function
导入时使用:
import * as config from "./config";
(这道题和Frequent issue with TypeScript and preferring import over require是不一样的,这道题是关于exports的,什么应该是两种等价的用法,另一道题是关于imports的。)
最佳答案
export const config = ...
就是所谓的“命名导出”,它将 config
变量添加到模块导出的名称列表中。您可以查看 es6 导出语句的各种变体 here ,这个特定的对应于第一个示例的第 4 行(注意 'also var, const' 注释):
export let name1 = …, name2 = …, …, nameN; // also var, const
并且可以与“named import* like”一起使用
import {config} from '...';
export = config
完全不同,它是 typescript-only export assignment .文档说它应该作为 import config = require(...)
导入,这又是仅限 typescript 的特殊语法。
使用当前版本的 TypeScript,导出赋值也可以导入为
import * as config from 'module';
but there is breaking change in the works ,在未来(可能尽快 2.8)这个导入将停止与导出 assingment 一起工作,并且必须写成
import config from 'module';
关于javascript - 关于 `export` 用法的功能等效性的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48369531/