语法检测
\Syntax detection
版本历史
| 版本 | 变更 |
|---|---|
| v22.7.0, v20.19.0 | 语法检测默认启用。 |
| v21.1.0, v20.10.0 | 新增于: v21.1.0, v20.10.0 |
\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
.jsextension or no extension; and either no controllingpackage.jsonfile or one that lacks atypefield. -
当未指定
--input-type时,字符串输入(--eval或STDIN)。\String input (
--evalorSTDIN) 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 中有效)。\
importstatements (but notimport()expressions, which are valid in CommonJS). -
export声明。\
exportstatements. -
import.meta参考文献。\
import.metareferences. -
await位于模块的顶层。\
awaitat the top level of a module. -
CommonJS 封装器变量的词法重新声明(
require、module、exports、__dirname、__filename)。\Lexical redeclarations of the CommonJS wrapper variables (
require,module,exports,__dirname,__filename).