我無法在 Azure Function 中使用包p-map。我收到以下錯誤:
Worker failed to load function: 'serverless' with function id: '<id>'.
Result: Failure
Exception: Worker was unable to load function serverless: 'Error [ERR_REQUIRE_ESM]: require() of ES Module <es-module> from /usr/local/Cellar/azure-functions-core-tools@4/4.0.4483/workers/node/worker-bundle.js not supported.
Instead change the require of index.js in /usr/local/Cellar/azure-functions-core-tools@4/4.0.4483/workers/node/worker-bundle.js to a dynamic import() which is available in all CommonJS modules.'
該專案是按照Azure 檔案中的步驟創建的。以下在 index.ts 中:
import { AzureFunction, Context, HttpRequest } from "@azure/functions";
import pMap from "p-map";
import got from "got";
const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
const sites = [
'https://avajs.dev',
'https://github.com'
];
const mapper = async site => {
const {requestUrl} = await got.head(site);
return requestUrl;
};
const result = await pMap(sites, mapper, {concurrency: 2});
context.res = {
// status: 200, /* Defaults to 200 */
body: result
};
};
export default httpTrigger;
我的 tsconfig.json 如下所示:
{
"compilerOptions": {
"module": "es2020",
"target": "es2020",
"outDir": "dist",
"rootDir": ".",
"sourceMap": true,
"strict": false,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true
}
}
最后,這是我的 package.json:
{
"name": "azure-functions-test",
"version": "1.0.0",
"description": "",
"type": "module",
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"prestart": "npm run build",
"start": "func start",
"test": "echo \"No tests yet...\""
},
"dependencies": {
"got": "^12.0.4",
"p-map": "^5.3.0"
},
"devDependencies": {
"@azure/functions": "^3.0.0",
"typescript": "^4.0.0"
}
}
p-map 嚴格來說是一個 ES 模塊,不能在 CommonJS 專案中使用。
我是否遺漏了什么,或者只是無法在 Azure Functions 中使用 ES 模塊包?提前致謝。
上述代碼的 GitHub 存盤庫,用于在本地進行測驗:azure-functions-test
uj5u.com熱心網友回復:
我通過將 index.ts 檔案重命名為 index.mts 解決了我的問題。npm run build這在我的 dist 檔案夾中構建了一個 index.mjs 檔案(運行后),它解決了這個問題。
需要注意的一件事是,您還必須編輯 function.json 的 scriptFile 鍵,以便它使用您的 .mjs 檔案而不是不存在的 .js 檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/475931.html
