繁体   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