DEV Community

Koutaro Chikuba
Koutaro Chikuba

Posted on

How to build firebase function by webpack

Why

Cloud Function for Firebase has node v6.11.x. It's too old for node.js developer and anyway we need our own build stack. For example, I'm babel and flow user.

In addition, in isomorphic environment like SSR, packages are expected same version. So I think bundling all source into one script is most easy solution to publish.

How to build

My project dirs.

package.json
firebase.json
functions/
  _dist/ # generated by webpack
    index.js
    package.json
  index.js # entry point
  webpack.config.js
Enter fullscreen mode Exit fullscreen mode
// functions/webpack.config.js
const pkg = require('../package')
const GenerateJsonPlugin = require('generate-json-webpack-plugin')

// Set externals that you don't want to build by webpack
const externals = [
  'firebase-admin',
  'firebase-functions'
]

const genPackage = () => ({
  name: 'functions',
  private: true,
  main: 'index.js',
  license: 'MIT',
  dependencies: externals.reduce(
    (acc, name) =>
      Object.assign({}, acc, {
        [name]:
          pkg.dependencies[name] ||
          pkg.devDependencies[name]
      }),
    {}
  )
})

module.exports = {
  entry: [__dirname + '/index.js'],
  output: {
    path: __dirname + '/_dist',
    filename: 'index.js',
    libraryTarget: 'commonjs'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/
      }
    ]
  },
  externals: externals.reduce(
    (acc, name) => Object.assign({}, acc, { [name]: true }),
    {}
  ),
  plugins: [new GenerateJsonPlugin('package.json', genPackage())]
}
Enter fullscreen mode Exit fullscreen mode

This webpack build functions/_dist/*.

Write your firebase.json

{
  "functions": {
    "source": "functions/_dist"
  },
  "hosting": {
    "rewrites": [
      {
        "source": "/api/hello",
        "function": "hello"
      }
    ]
  }
}

Enter fullscreen mode Exit fullscreen mode

Let's build and deploy.

$ npm i -g firebase-tools webpack
$ webpack --config functions/webpack.config.js
$ cd functions/_dist/; npm install
$ firebase deploy only functions
Enter fullscreen mode Exit fullscreen mode

You can add this task as npm scripts.

Top comments (0)