我们正在尝试将现有应用程序从 Serverless 3 移植到 sst。
serverless.yml 有一个 custom.esbuild 部分:
custom:
esbuild:
bundle: true
minify: false
plugins: ./esbuild-plugins.js
sourcemap: true
target: es2022
esbuild-plugins.js 定义为:
const { default: graphqlLoaderPlugin } = require("@luckycatfactory/esbuild-graphql-loader");
const { nodeExternalsPlugin } = require("esbuild-node-externals");
const fs = require("fs-extra");
const path = require("path");
const copyPlugin = ({ from, to }) => {
return {
name: "copy",
setup(build) {
const target = build.initialOptions.outfile
? path.dirname(build.initialOptions.outfile)
: path.resolve(build.initialOptions.outdir);
build.onEnd(() => fs.copySync(from, path.join(target, to), { overwrite: true }));
},
};
};
// eslint-disable-next-line no-undef
module.exports = [
graphqlLoaderPlugin(),
nodeExternalsPlugin(),
copyPlugin({
from: "src/type-defs",
to: "./type-defs",
}),
];
现在,当我尝试将插件部分移至 sst 时,问题就出现了。这是相关函数的堆栈的相关部分:
import * as graphqlLoaderPlugin from "@luckycatfactory/esbuild-graphql-loader";
export function API({ stack }: StackContext) {
const { stackName, stage } = stack;
console.log(`Deploying ${stackName} to stage: ${stage}`);
const function = new Function(stack, "function", {
handler: "./src/lambda.handler",
runtime: "nodejs20.x",
memorySize: 768,
copyFiles: [{ from: "./src/type-defs" }],
nodejs: {
esbuild: {
plugins: [graphqlLoaderPlugin.default()],
},
},
environment: {
/* ...*/
},
});
const api = new ApiGatewayV1Api(stack, "api", {
routes: {
"ANY /graphql": {
function: function,
cdk: {
method: {
apiKeyRequired: true,
},
},
},
},
});
/* omitted usageplans, apikeys and other goodness */
使用当前的 esbuild 配置会产生以下错误:
TypeError: graphqlLoaderPlugin.default is not a function
同样如此,当我更改为导入到
import graphqlLoaderPlugin from "@luckycatfactory/esbuild-graphql-loader";
并且插件调用graphqlLoaderPlugin()
时。
使用 sst 时将插件加载到 esbuild 中的正确语法是什么?
我发现使用 require 通过
js
模块导入它就可以了。
const { default: graphqlLoaderPlugin } = require("@luckycatfactory/esbuild-graphql-loader");
module.exports = [
graphqlLoaderPlugin()
]
将此模块导入到 sst 堆栈中,现在已成功构建。