node.js - 运行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.js
和index.cjs
文件,但index.js
正在选择文件。
当我运行作为文件的编译输出时,一切都很好.cjs
。
有没有办法让节点知道我希望一切都在 commonjs 下运行。
解决方案
我认为没有办法让节点做你想做的事。我有一个类似的项目,主要项目是 commonjs,但其中一个库是 esm,或者它正在使用的库是 esm。我不记得具体的细节,但这是一种皇家的痛苦。
基本的解决方法是使用esm
给import
你问题的库。很可能一旦你这样做了,你最终会遇到第二层问题。
// 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())
}
推荐阅读
- ios - Swift:Firestore 子集合、自定义对象和监听器
- mysql - --skip-grant-tables 选项不能执行语句
- html - 当我们在 Google Chrome 开发者工具上使用“删除元素”时,它真的会从实时全局服务器中删除该元素吗?
- python - 如何获取 GCP Cloud Function 实际调用的 URL,包括查询参数(Python 运行时)
- angular - 通过 Angular 服务订阅
- google-play-developer-api - paymentState 不会从试用期改变
- java - 使用spring 4从系统环境变量中获取数据
- c# - 如果我知道大部分时间结果将被缓存,则避免 async/await
- r - 如何合并长度不等但已知块长度的数据帧?
- r - 建立回归结果表