javascript - 为什么 import xxx = require ('package' ) 比 const xxx = require ('package' ) 更好?这是真的吗?

标签 javascript typescript

有人建议我:

import xxx = require('package');

优于:

const xxx = require('package');  

并保留所有类型定义。这是真的? 看起来第一种语法可能更好,但是当像这样 import 和 require 一起使用时我仍然感到困惑。

最佳答案

import xxx = require('package'); 是旧的 typescript 导入模块语法,建议您切换到新的 ES 标准导入语法。如果模块这样做 not support it ,这可能并不总是可能的:

Both CommonJS and AMD generally have the concept of an exports object which contains all exports from a module.

They also support replacing the exports object with a custom single object. Default exports are meant to act as a replacement for this behavior; however, the two are incompatible. TypeScript supports export = to model the traditional CommonJS and AMD workflow.

When exporting a module using export =, TypeScript-specific import module = require("module") must be used to import the module

如果您在 import xxx = require('package')const xxx = require('package') 之间做出选择,我肯定会使用 导入版本。

导入版本会触发 typescript 机制来解析模块并正确键入导入变量(利用该模块的任何模块定义)。

const 版本只是对节点定义中定义的函数的函数调用:

declare var require: NodeRequire;
interface NodeRequire extends NodeRequireFunction { /*...*/ }

interface NodeRequireFunction {
    (id: string): any; // just returns any.
}

正如您所看到的,此函数对于任何给定的模块名称都会返回 any,因此实际上保存导入的变量将是 any 类型,因此您不会受益来自您可能为该模块安装的任何类型。

关于javascript - 为什么 import xxx = require ('package' ) 比 const xxx = require ('package' ) 更好?这是真的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55887063/

相关文章:

javascript - 使用 JavaScript 选择下拉选项

javascript - Jquery 换行符替换为 br 标签不起作用?

html - 实时数据 Angular

angular - 在 Angular 中使用可观察量进行 http 请求的最佳方法是什么?

javascript - KnockoutValidation 和条件必需规则

javascript - 向页面添加动态脚本资源

javascript - 尝试在生产中编译时 Meteor UglifyJS 错误

TypeScript:在多个文件中声明类的函数

visual-studio - TypeScript VS - 编译错误但没有设计时错误

javascript - 为什么javascript ssh2在使用shell时会陷入无限循环