为什么某些Typescript模块名称以字符串形式给出?

编程入门 行业动态 更新时间:2024-10-25 08:20:07
本文介绍了为什么某些Typescript模块名称以字符串形式给出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

通常,Typescript模块的声明类似于

Typically, Typescript modules are declared like

declare module MyModule { .... }

但有时我也会看到

declare module "MyModule" { .... }

我想知道以字符串形式给出名称的目的是什么?

I am wondering what is the purpose of giving the name as a string?

我检查了打字稿文档并找到

这是其导入实体为可调用函数的模块的常用模式

This is a common pattern for modules whose imported entities are callable functions

我尝试同时编译MyModule和"MyModule",它们都编译为同一件事.这是否意味着带引号或不带引号是等效的,并且决定使用引号就像将大写字母用作类名,或将接口名以I等开头.

I tried compiling both MyModule and "MyModule" and they compile to the same thing. Does this mean that with or without quotes are equivalent, and deciding to use them is just like using capital letters for class names, or starting interface names with I etc.?

推荐答案

如打字稿文档,两种样式之间存在差异. module x {等同于namespace x {,而module "x" {与其他两个都不相同.这绝对令人困惑,这就是为什么文档在所有情况下都使用后一种语法的原因.

As outlined in the Typescript docs, there is a difference between the two styles. module x { is equivalent to namespace x {, while module "x" { is unlike either of the other two. This is definitely confusing, which is why the documentation using the latter syntax in all cases.

然后必须问一个问题,名称空间和所谓的外部模块(即用引号声明的模块)之间有什么区别?

The question then must be asked, what is the difference between a namepsace and a so-called external module (i.e., a module that is declared with quotes)?

我们从文档中获得了一些见识:

We get some insight from the docs:

就像命名空间一样,模块可以包含代码和声明.主要区别在于模块声明了它们的依赖关系.

Just like namespaces, modules can contain both code and declarations. The main difference is that modules declare their dependencies.

模块还依赖于模块加载器(例如CommonJs/Require.js).

Modules also have a dependency on a module loader (such as CommonJs/Require.js).

基本上,使用引号表示它确实是传统Javascript意义上的模块,需要使用显式导入.如果没有引号,则只需创建一个全局对象,而无需任何明确的require即可对其进行引用和利用.

Essentially, using the quotes indicates that it is indeed a module in the traditional Javascript sense that requires explicit import to be used. Without the quotes, you just create a global object that can be referenced and utilized without any explicit requires.

更多推荐

为什么某些Typescript模块名称以字符串形式给出?

本文发布于:2023-11-06 09:52:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563366.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   模块   形式   名称   Typescript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!