且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Closure Compiler中将node_modules定义为externs?

更新时间:2023-11-06 11:23:34

问题是您希望编译器以某种方式识别某些 require 调用是内部的,即所需的模块应该由编译器作为源处理,而其他的是外部的,所以应该保持独立。目前没有一种好方法来处理这种情况。

The issue is that you wish for the compiler to somehow recognize that certain require calls are internal, namely that the required module should be processed by the compiler as source, and others are external so should be left alone. There isn't a good way to handle this situation currently.

在这种情况下,您将完全省略任何 require 语句到外部模块。编译器只处理带有内部require语句和模块的代码。编译之后,您将预先设置外部需求声明:

In this scenario you would completely omit any require statements to external modules. The compiler would only process code with internal require statements and modules. After compilation, you would prepend the external require statements:

var crypto = require('crypto');



要编译的来源



Source To Be Compiled

console.log(crypto);

因为 crypto 在extern中声明,编译器将正确识别类型和符号名称。

Because crypto is declared in an extern, the compiler will correctly recognize the type and symbol name.

当指定 - process_common_js_modules 时,编译器会识别 require 声明并以与宏在其他语言中工作的方式类似的方式扩展它们。通过别名应保留在外部的 require 语句,编译器将无法识别它们,因此不会扩展它们。

When the --process_common_js_modules is specified, the compiler recognizes require statements and expands them in a similar fashion to the way macros work in other languages. By aliasing the require statements that should remain external, the compiler will not recognize them and thus not expand them.

var externalRequire = require;
/** @suppress {duplicate} this is already defined in externs */
var crypto = externalRequire('crypto');
console.log(crypto)