有人建议我:
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-specificimport 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/