【问题标题】:How to write Google Cloud Functions in TypeScript with webpack如何使用 webpack 在 TypeScript 中编写 Google Cloud Functions
【发布时间】:2021-08-13 23:25:15
【问题描述】:

我正在尝试用 TypeScript 编写 Google Cloud Function 的代码。这个想法是源代码库将具有为多个云函数定义的处理函数,每个函数位于不同的文件中,并且所有处理程序共享一些代码。我可以使用 tsc 编译我的源代码,但我需要对它们进行 webpack 以生成 Cloud Functions 将加载的单个 index.js。所以我需要 webpack 将处理程序合并到一个文件中。

这是我的tsconfig.json

{
  "compilerOptions": {
    "incremental": true,
    "target": "es2016",
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node"
  },
  "include": ["src/**/*.ts"]
}

这是来自src/TheHandler.ts 的一个处理程序的代码:

import { EventFunction } from "@google-cloud/functions-framework";

export const TheHandler: EventFunction = (
  message,
  context
) => {
  console.log(message);
  console.log(context);
};

这可以毫无问题地编译成 JavaScript。

现在我将它输入到 webpack 中。这是我的webpack.config.js

const path = require("path");
const fs = require("fs");
const nodeExternals = require("webpack-node-externals");

const files = fs
  .readdirSync("src")
  .filter((item) => item.match(/\.ts$/))
  .map((file) => `./src/${file}`);

module.exports = {
  mode: "production",
  entry: files,
  externalsPresets: { node: true },
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [".ts"],
  },
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
};

这导致dist/bundle.js 为空,如 webpack 输出所证实:

asset bundle.js 0 bytes [compared for emit] [minimized] (name: main)
./src/TheHandler.ts 612 bytes [built] [code generated]
webpack 5.50.0 compiled successfully in 1937 ms

这是模块格式问题还是 webpack 试图在 ts-loader 编译 src/TheHandler.ts 之前捆绑所有内容?还是别的什么?

【问题讨论】:

    标签: typescript webpack google-cloud-platform google-cloud-functions


    【解决方案1】:

    我必须在webpack.config.js 中将libraryTarget: "commonjs2" 添加到output

    【讨论】:

      【解决方案2】:

      如您所见,您需要设置 libraryTarget 以构建一个 webpack 包,该包本身可以由 webpack 构建之外的另一个模块导入(例如,从云函数)。

      使用webpack-cloud-functions(我是其中的作者)您可能会更轻松(并且在可靠的 HMR 方面拥有更好的开发人员体验)。它抽象了您使用带有云功能的 webpack 所需的大部分配置,包括配置 libraryTarget

      【讨论】:

        猜你喜欢
        • 2021-12-26
        • 1970-01-01
        • 2020-07-20
        • 2017-10-03
        • 1970-01-01
        • 2018-12-03
        • 2022-01-08
        • 1970-01-01
        • 2023-03-16
        相关资源
        最近更新 更多