簡體   English   中英

在 Azure Typescript 函數中使用 ES 模塊包

[英]Using ES Module packages in Azure Typescript Function

我無法在我的 Azure 函數中使用包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

我通過將 index.ts 文件重命名為 index.mts 解決了我的問題。 這在我的 dist 文件夾中構建了一個 index.mjs 文件(在運行npm run build之后),它解決了這個問題。

需要注意的一件事是,您還必須編輯 function.json 的 scriptFile 鍵,以便它使用您的 .mjs 文件而不是不存在的 .js 文件。

根據 Node.js 網站上的文檔,在package.json中指定"type": "module"還應該指示 Node 是否應該使用 ESM。

以下是我為讓 ESM 在我的 Function App 中為我的函數工作所做的工作:

tsconfig.json

{
  "compilerOptions": {
    "module": "ESNext",
    "target": "ESNext",
    "moduleResolution": "Node",
    "outDir": "dist",
    "rootDir": ".",
    "sourceMap": true,
    "strict": false,
    "noImplicitAny": true,
    "noUnusedLocals": true
  }
}

一些相關的功能應用程序設置:

WEBSITE_NODE_DEFAULT_VERSION~16 (使用 Node.js 16 運行時運行) FUNCTIONS_EXTENSION_VERSION~4

暫無
暫無

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

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