ope*_*sas 5 javascript import node.js es6-modules
我正在尝试使用 pkg 将节点应用程序打包为 exe,并且我想使用 ES6 导入。
我的 src/app.js 中有这样的内容:
import express from 'express'
const app = express()
const eco = (req, res) => {
const { method, url, headers, query } = req
res.json({ method, url, headers, query })
}
app.all('/', eco)
app.listen(3000, () => console.log(`listening on http://localhost:3000`))
Run Code Online (Sandbox Code Playgroud)
在我的 package.json 中我有:
{
"name": "pkg-test",
"version": "1.0.0",
"description": "",
"main": "src/app.js",
"type": "module",
"type": "module",
"scripts": {
"build": "pkg --targets=node12-win-x64 --output=iisnode-pkg.exe --options experimental-modules src/app.js",
"start": "node --experimental-modules src/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"pkg": "^4.4.0"
}
}
Run Code Online (Sandbox Code Playgroud)
npm start 工作正常
import express from 'express'
const app = express()
const eco = (req, res) => {
const { method, url, headers, query } = req
res.json({ method, url, headers, query })
}
app.all('/', eco)
app.listen(3000, () => console.log(`listening on http://localhost:3000`))
Run Code Online (Sandbox Code Playgroud)
但npm run build给出了一个减弱,然后运行 exe 抛出一个错误:
{
"name": "pkg-test",
"version": "1.0.0",
"description": "",
"main": "src/app.js",
"type": "module",
"type": "module",
"scripts": {
"build": "pkg --targets=node12-win-x64 --output=iisnode-pkg.exe --options experimental-modules src/app.js",
"start": "node --experimental-modules src/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"pkg": "^4.4.0"
}
}
Run Code Online (Sandbox Code Playgroud)
$ npm start
> iisnode-pkg@1.0.0 start C:\data\devel\apps\tmp\iisnode-pkg
> node --experimental-modules src/app.js
(node:10668) ExperimentalWarning: The ESM module loader is experimental.
welcome to iisnode-pkg
iisnode-pkg listening on http://localhost:3000
Run Code Online (Sandbox Code Playgroud)
似乎--options experimental-modules没有考虑 package.json 中构建脚本的参数。
知道如何使用从与 pkg 打包的节点应用程序导入的 ES6 模块吗?
如果找到解决方案,我会发布更新,但这似乎不再可能。
ESM 模块不再是实验性的,它们是 Node 的核心部分,也是推荐使用的约定。
进行一个简单的测试后,当前的 pkg 会生成一条警告,导致 ESM 模块文件因此错误而被跳过,因此在运行时无法加载该模块。我不确定这个问题是什么时候发生的,但我在这里发布了问题的简单再现: https: //github.com/appurist/pkgtest/
我还在此处添加了对(已关闭)GitHub 问题的评论: https://github.com/vercel/pkg/issues/641#issuecomment-870013906
似乎没有任何解决方法,因为问题似乎就在pkg其本身。
确保您运行的是最新版本的 Node。 Node.js 中 ESM 的实现在版本 12.0.0 中发生了变化。10.x 中不支持“type”:“module”。
您需要添加options到配置中pkg。所以,在package.json:
"pkg": {
"options": ["experimental-modules"]
}
Run Code Online (Sandbox Code Playgroud)
节点文档: https: //nodejs.org/api/esm.html
| 归档时间: |
|
| 查看次数: |
5919 次 |
| 最近记录: |