首页 > 解决方案 > 运行nodemon时在一个依赖的commonjs下运行时选择commonjs文件

问题描述

我正在运行节点 14。

我有一个在 package.json 中有这个的包

  "main": "dist/index.js",
  "type": "commonjs",

没有浏览器或模块字段。

这是我编译为.cjs输出的打字稿项目。

问题是当我像这样启动nodemon时:

nodemon --watch 'src/**/*' -e ts,tsx --exec ts-node ./src/index.ts

我收到此错误:

错误 [ERR_REQUIRE_ESM]:必须使用导入来加载 ES 模块:/Users/blah/dist/index.js

有问题的模块有module“主and浏览器fields but its type is模块”。

它有index.jsindex.cjs文件,但index.js正在选择文件。

当我运行作为文件的编译输出时,一切都很好.cjs

有没有办法让节点知道我希望一切都在 commonjs 下运行。

标签: node.jsnodemon

解决方案


我认为没有办法让节点做你想做的事。我有一个类似的项目,主要项目是 commonjs,但其中一个库是 esm,或者它正在使用的库是 esm。我不记得具体的细节,但这是一种皇家的痛苦。

基本的解决方法是使用esmimport你问题的库。很可能一旦你这样做了,你最终会遇到第二层问题。

// example
const esmImport = require('esm')(module)
const {CookieJar, fetch} = esmImport('node-fetch-cookies')

动态导入也为我解决了这个问题。

async init() {
        const { CookieJar } = await import('node-fetch-cookies')
        this.cookieJar = new CookieJar()
        this.cookieJar.addCookie(`username=${this._user}`, this._url.toString())
        this.cookieJar.addCookie('hippa=yes', this._url.toString())
    }

推荐阅读