【问题标题】:select the commonjs file when running under commonjs of a dependency when running nodemon运行nodemon时在一个依赖的commonjs下运行时选择commonjs文件
【发布时间】:2021-03-15 19:42:48
【问题描述】:

我正在运行节点 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]:必须使用 import 来加载 ES 模块:/Users/blah/dist/index.js

有问题的模块有module, 'mainandbrowserfields but its type ismodule`。

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

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

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

【问题讨论】:

  • 如果我的回答对你不起作用,那么请你证明一个 MVP。

标签: node.js nodemon


【解决方案1】:

我认为没有办法让节点做你想做的事。我有一个类似的项目,其中主要项目是 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())
    }

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,我使用单引号作为多值参数,例如 `--exec' 来解决它。

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

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 1970-01-01
      • 2014-01-14
      • 2012-05-23
      • 1970-01-01
      相关资源
      最近更新 更多