Ou *_* Ye 3 javascript azure node.js
尝试在azure应用程序服务上托管一个简单的nodejs api服务器,但当azure尝试部署它时出现以下错误
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: D:\home\site\wwwroot\server.js
require() of ES modules is not supported.
require() of D:\home\site\wwwroot\server.js from D:\Program Files (x86)\iisnode\interceptor.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename server.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from D:\home\site\wwwroot\package.json.
Run Code Online (Sandbox Code Playgroud)
检查了azure应用程序服务,WEBSITE_NODE_DEFAULT_VERSION设置为~14,并且Web应用程序中安装的nodejs版本是v14.15.0。不要认为这个版本的节点不再有导入导出问题。
该代码在本地运行得很好
node server.js
# or
node --experimental-modules server
Run Code Online (Sandbox Code Playgroud)
不知道为什么它在天蓝色中失败
我的代码如下:
服务器.js
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: D:\home\site\wwwroot\server.js
require() of ES modules is not supported.
require() of D:\home\site\wwwroot\server.js from D:\Program Files (x86)\iisnode\interceptor.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename server.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from D:\home\site\wwwroot\package.json.
Run Code Online (Sandbox Code Playgroud)
包.json
{
"name": "my_package",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node --experimental-modules server",
"test": "mocha"
},
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我将导入和导出更改为 require,那么它将在 azure web 应用程序中运行,看来 azure iisnode 与 emac6 还不兼容?有谁知道?
除了使用 babel 将 emac6 转换为 emac5 之外,有人还有其他解决办法吗?因为我在执行和运行转译的 emac5 代码时遇到一些问题。
谢谢
这可以通过在您的旁边添加一个新文件server.js
并将其配置为应用程序服务(或更具体地说是iisnode)的入口点(请参阅您的web.config
)来解决。
让我们调用新文件run.cjs
并仅将以下行放入其中:
import("./server.js");
Run Code Online (Sandbox Code Playgroud)
文件cjs
扩展名很重要,因为它告诉 Node 该文件不是 ES 模块,正如它所期望的那样,因为"type": "module"
在您的package.json
. 这允许其他 CommonJS 文件包含我们的新文件 - 即 iisnode 的interceptor.js
. 它再次导入server.js
然后作为 ES 模块运行良好。