LoginSignup
2
1

More than 3 years have passed since last update.

cloud functionをwebpackでバンドルする環境(TS)

Posted at

モチベーション

  • 相応数のCFを使うようなプロジェクトに膨れてきたのでバンドルサイズを下げてbuildの速度向上とデプロイの安定化
  • node10以降するにあたってついでに改善する
index.ts
const functions = {
   name: 'path/to/file',
   ...
}

for (let func in functions) {
    if (!process.env.K_SERVICE || process.env.K_SERVICE === name) {
      exports[func] = require(`./funcs/${functions[func]}`);
    }
}

環境変数K_SERVICEはnode10以上

babel.rc
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "corejs": 3,
        "targets": {
          "node": "10"
        }
      }
    ],
    "@babel/preset-typescript"
  ]
}

webpack.config.js
const nodeExternals = require('webpack-node-externals');
const GenerateJsonPlugin = require('generate-json-webpack-plugin');
const path = require('path');

module.exports = {
  target: 'node',
  mode: process.env.NODE_ENV,
  entry: './index.ts',
  output: {
    filename: 'index.js',
    path: `${__dirname}/dist`,
    libraryTarget: 'commonjs',
  },
  plugins: [
    // deployに必要なのでdistにコピー
    new GenerateJsonPlugin('package.json', require('./package')),
  ],
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js', '.json'],
    alias: {
      root: __dirname,
      funcs: path.resolve(__dirname, 'funcs'),
    },
  },
  externals: [nodeExternals()],
};

package.json
{
  "engines": {
    "node": "10"
  },
  "scripts": {
    "deploy": "yarn run build && firebase deploy --only functions",
    "build": "NODE_ENV=production webpack  && cp .npmrc ./dist/.npmrc",
  },
}

個別、一括のデプロイどちらも正常に動作します。
ベータ版としてNode12がサポートされましたが、自分の環境では各ファイル10->12に変更するだけで動作しているようでした

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1