I'm currently facing a challenge while coding a Google Cloud Function using TypeScript. The concept involves having handler functions defined for various Cloud Functions in separate files within the source repository, along with some code that is shared among all handlers. After compiling my sources with tsc, I realized the need to webpack them in order to generate a single index.js
file that can be loaded by Cloud Functions. Consequently, I require webpack to merge all handlers into one file.
Below is my configuration file 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"]
}
Shown below is the code for a handler from src/TheHandler.ts
:
import { EventFunction } from "@google-cloud/functions-framework";
export const TheHandler: EventFunction = (
message,
context
) => {
console.log(message);
console.log(context);
};
The above code compiles to JavaScript without encountering any issues.
However, upon feeding it into webpack, using the following 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"),
},
};
The result is an empty dist/bundle.js
, as confirmed by the webpack output:
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
Could this issue be related to the module format or webpack attempting to bundle everything before ts-loader compiles src/TheHandler.ts
? Or could it be something else entirely?