Bundling PostGraphile with Webpack使用 Webpack 打包 PostGraphile
PostGraphile is designed to be run as a standard Node.js application on the
server, using the built in require functionality which reads code from the
filesystem. However, if system startup time is a critical metric in your
environment (for example on serverless environments) this "searching and loading
from disk" behaviour can be very expensive. One way to solve this problem is
to bundle your code up into a single JavaScript file so that no filesystem
access is required.
PostGraphile 默认作为标准的 Node.js 服务端应用运行,通过内置的 require 机制从文件系统按需加载代码。然而,在 Serverless 等对冷启动耗时极为敏感的环境中,频繁“从磁盘查找并读取文件”的开销会非常高。解决这一问题的常见办法,是将代码打包成单个 JavaScript 文件,从而彻底避免启动时的磁盘 I/O。
Assuming your plugins all support it, rather than bundling up postgraphile
itself, we recommend exporting your schema as executable
code using graphile-export and then bundling the
resulting schema file for production usage. This will typically result in a
smaller bundle and faster startup times. (If it doesn't, your schema might want
some pruning!)
只要你使用的插件全部支持,与其直接打包 postgraphile 本身,我们更建议先使用 graphile-export 将 schema 导出为可执行代码,再针对导出后的 schema 文件进行生产环境打包。这样做通常能获得更小的包体积和更快的启动速度。(如果效果不理想,说明你的 schema 可能还需要适当裁剪!)
Webpack is a tool that you can use to bundle JavaScript code up; here’s an example webpack configuration you might use:
Webpack 是一款常用的 JavaScript 代码打包工具,下面是一个可供参考的 Webpack 配置示例:
const webpack = require("webpack");
const TerserPlugin = require("terser-webpack-plugin");
const path = require("path");
module.exports = {
mode: "production",
// The result of exporting your schema
entry: "./exported-schema.mjs",
output: {
path: path.resolve(__dirname),
// Where to save the resulting packed JS file
filename: "exported-schema.webpacked.js",
library: {
type: "commonjs",
},
},
plugins: [
new webpack.DefinePlugin({
// For efficiency, enable production environment
"process.env.NODE_ENV": JSON.stringify("production"),
"process.env.GRAPHILE_ENV": JSON.stringify("production"),
}),
],
target: "node", // use require() & use NodeJs CommonJS style
externalsPresets: {
node: true, // in order to ignore built-in modules like path, fs, etc.
},
performance: {
maxEntrypointSize: 2000000,
maxAssetSize: 2000000,
},
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
// Without this, some bugs may occur
keep_classnames: true,
},
}),
],
},
};
Install webpack with yarn add --dev webpack webpack-cli and then you can run
it as yarn webpack.
执行 yarn add --dev webpack webpack-cli 安装 Webpack,之后即可运行 yarn webpack 完成打包。
A more invasive and optimized config can be found in our Lambda example; though it has not yet been updated for V5 - please do submit a PR!
你可以在我们的 Lambda 示例项目中查看更深度、更激进的优化配置;不过该示例尚未针对 V5 更新——欢迎提交 PR 协助完善!