javascript - 关于 `export` 用法的功能等效性的困惑

标签 javascript node.js typescript

不应该

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/

相关文章:

javascript - 无法在 Angular 9 中进行默认导入

javascript - 在rabbitmq中获取路由/绑定(bind) key

javascript - ol-ext : map control bar is not show on the map

mysql - 从 sequelize 查询返回一个值

arrays - typescript - 初始化二维数组错误

javascript - 如何区分 javascript 声明 typescript 文件中的静态方法和实例方法?

javascript - 允许 div 随页面滚动而滚动,但仅在父 div 内

javascript - 如何从javascript返回多个值到jsp

node.js - 如何在 Firebase 函数中使用 koa.js + next

forms - 使用nodejs和connect-form上传文件