簡體   English   中英

我可以在 IBM Cloud Functions (node.js) 中使用 ES 模塊還是僅支持 Common JS?

[英]Can I use ES modules in IBM Cloud Functions (node.js) or is only Common JS supported?

當我從包含簡單estest.js的 zip 文件創建 Node.js v16 函數操作時:

function main(params) {
    return { message: 'Hello World' };
}

package.json包含"type": "module"我得到:

{
  "error": "Initialization has failed due to: Error [ERR_REQUIRE_ESM]: require() of ES Module /nodejsAction/1AfjbP59/estest.js from /nodejsAction/runner.js not supported.estest.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains \"type\": \"module\" which declares all .js files in that package scope as ES modules.\nInstead rename estest.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change \"type\": \"module\" to \"type\": \"commonjs\" in /nodejsAction/1AfjbP59/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).\n\n    at eval (eval at <anonymous> (/nodejsAction/runner.js:51:31), <anonymous>:1:1)\n    at /nodejsAction/runner.js:51:31"
}

我沒有找到任何聲明僅支持舊的 Common JS 樣式的 IBM Cloud 文檔。

編輯:

使用創建的操作:

ibmcloud fn action create test/estest estest.zip --kind nodejs:16

經過更多研究,我得出結論,動作本身不能是 ES 模塊。

我嘗試將其重命名為estest.mjs (在package.json中沒有"type":"module" ),它給出了:

{"error": "Initialization has failed due to: Error [ERR_REQUIRE_ESM]: require() of ES Module /nodejsAction/azrfHRlh/estest.mjs not supported.\nInstead change the require of /nodejsAction/azrfHRlh/estest.mjs to a dynamic import() which is available in all CommonJS modules.\n    at eval (eval at <anonymous> (/nodejsAction/runner.js:51:31), <anonymous>:1:1)\n    at /nodejsAction/runner.js:51:31"}

我認為這是由於runner.js中的require() (嘗試加載我的estest.mjs ES 模塊的 IBM Cloud / OpenWhisk 實現):

//  The module to require.
let whatToRequire = index !== undefined ? path.join(moduleDir, index) : moduleDir;
let handler = eval('require("' + whatToRequire + '").' + main);

require()不支持 ES 模塊: https ://nodejs.org/api/esm.html#esm_require 。

解決方案

正如錯誤消息所暗示的那樣,解決方案是創建一個 CommonJS 包裝器( estest.cjs ),它執行我的 ES 模塊estest.mjs的動態import()並在package.json中使用"main": "estest.cjs"

estest.cjs
async function main(params) {
    const { mjstest } = await import('./estest.mjs');
    return mjstest(params);
}

exports.main = main;
estest.mjs
export const mjstest = (params) => {
    return { message: `Hello ${params.name || 'World'}` };
}
包.json
{
    "name": "estest",
    "version": "1.0.0",
    "main": "estest.cjs"
}

我認為線索在錯誤消息中:

supported.estest.js is treated as an ES module file as it is a .js file

您是否嘗試將擴展名更改為supported.estest.mjs

package.json中指定節點版本可能也是值得的,例如。

  "engines": {
    "node": ">=16.x"
  },

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM