语法检测


¥Syntax detection

稳定性: 1.2 - 发布候选

¥Stability: 1.2 - Release candidate

Node.js 会检查不明确输入的源代码以确定其是否包含 ES 模块语法;如果检测到这样的语法,输入将被视为 ES 模块。

¥Node.js will inspect the source code of ambiguous input to determine whether it contains ES module syntax; if such syntax is detected, the input will be treated as an ES module.

不明确的输入定义为:

¥Ambiguous input is defined as:

  • 带有 .js 扩展名或没有扩展名的文件;并且没有控制 package.json 文件或缺少 type 字段。

    ¥Files with a .js extension or no extension; and either no controlling package.json file or one that lacks a type field.

  • 当未指定 --input-type 时,字符串输入(--evalSTDIN)。

    ¥String input (--eval or STDIN) when --input-typeis not specified.

ES 模块语法被定义为当评估为 CommonJS 时会抛出异常的语法。这包括以下内容:

¥ES module syntax is defined as syntax that would throw when evaluated as CommonJS. This includes the following:

  • import 语句(但不是 import() 表达式,它们在 CommonJS 中有效)。

    ¥import statements (but not import() expressions, which are valid in CommonJS).

  • export 声明。

    ¥export statements.

  • import.meta 参考文献。

    ¥import.meta references.

  • await 位于模块的顶层。

    ¥await at the top level of a module.

  • CommonJS 封装器变量的词法重新声明(requiremoduleexports__dirname__filename)。

    ¥Lexical redeclarations of the CommonJS wrapper variables (require, module, exports, __dirname, __filename).