【发布时间】: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