require() 在模块类型 nodejs 脚本中不起作用

Ada*_*yai 6 javascript node.js node-modules

在我的package.json文件中,我指定了我的nodejs应用程序的类型module,因为如果我不这样做,似乎我不能使用import语句。这是现在的样子:

{
  "name": "...",
  "version": "1.0.0",
  "description": "....",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "...."
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "lodash": "^4.17.15"
  },
  "type": "module"
}
Run Code Online (Sandbox Code Playgroud)

但是如果我将"type": "module"加到我的package.json文件中,我就不能再使用require语句了,因为我得到了一个ReferenceError: require is not defined错误。

如果我"type": "module"package.json 中删除该行,并将所有导入重写为 requires,则一切正常,没有错误。

我似乎无法找到任何迹象,这importrequire在同一个脚本不能混用或一起使用,我失去了一些东西在这里,或我有一些其它的错误?我怎样才能决定在同一个脚本中使用这两种语句?

为什么我需要这个,是因为我想要require一些基于动态路径的配置文件,并且只有当文件存在时,我认为我不能用import.

免责声明:我对 nodejs 服务器端编程比较陌生,所以我可能非常错误地处理这种情况,如果是这种情况,请根据我上面提到的原因给我一些建议。

注意:我从服务器终端运行这个节点脚本,而不是从浏览器。

T.J*_*der 14

但是如果我将"type": "module"加到我的package.json文件中,我就不require能再使用语句了,因为我得到了一个ReferenceError: require is not defined error.

对。要么/要么。要么使用 ESM(JavaScript 模块,type = "module"),要么使用 CJS(类似 CommonJS 的 Node.js 原生模块require)。

但是,如果您使用的是type="module"

  1. 您仍然可以使用 CJS 模块,只需通过import而不是require(或通过import()[dynamic import] 如有必要)导入它们。在此处此处查看详细信息。

  2. 您可以使用createRequire来有效地获得require可以在 ESM 模块中使用的函数,这使我们...

为什么我需要这个,是因为我想要require一些基于动态路径的配置文件,并且只有当文件存在时,我认为我不能用import.

这是正确的。你必须用createRequire它来代替(或readFileJSON.parse),更多在这里

createRequire 版本:

import { createRequire } from "module";
const require = createRequire(import.meta.url);
const yourData = require("./your.json");
Run Code Online (Sandbox Code Playgroud)