code smith

開発で日々の生活をもっと楽しく

firebase functionsのモジュールインポートでaliasを利用する

f:id:gaku3601:20220103104416j:plain Gakuです。
firebaseのfirebase functionsについて簡単なtipsを掲載したいと思います。

モジュールインポートのaliasについて

firebase functionsはtypescriptを導入し利用しているのですが、import部分で

import * from '../../util/baseComponent';

のようにデフォルト設定だと相対パスでのアクセスとなってしまい、階層が深いと'../'がかなり多くなって、嫌だったので

import * from '@/util/baseComponent';

のようにrootからのパスを@で絶対パスでアクセスできるようになれば楽なのにな〜と思ったので、その設定を入れてみました。

依存追加

npm install --save-dev webpack webpack-cli ts-loader webpack-node-externals

webpack周りを追加して設定していきます。

設定

まずはpackage.jsonでwebpackでbuildできるように設定します。

"scripts": {
    "lint": "eslint --ext .js,.ts .",
    "build": "webpack", // ★これに変更
    "serve": "npm run build && firebase emulators:start --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
},

firebase functionsのrootフォルダでwebpack.config.jsを作成し、以下のようにビルドの設定を記載します。

const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
    mode: 'production',
    entry: './src/index.ts',
    output: {
        filename: 'index.js',
        path: `${__dirname}/lib`,
        libraryTarget: 'this',
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.json'],
        alias: {
            '@': path.resolve(__dirname, './src'),
        },
    },
    target: 'node',
    module: {
        rules: [
            {
                test: /\.ts$/,
                exclude: /node_modules/,
                loader: 'ts-loader',
                options: {
                    configFile: path.resolve(__dirname, 'tsconfig.json'),
                },
            },
        ],
    },
    externals: [nodeExternals()],
};

これでモジュールインポートでaliasは利用できるのですが、私のIntelliJの環境だとエラーが出たのでIDEでもエラーが出ないようにtsconfg.jsに以下の設定を追加します。

  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017",
    "baseUrl": "./", //★追加
    "paths": { //★ 追加
      "@/*": ["src/*"],
    }
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}

以上です。この設定を行うことで、src/...へのアクセスは、どこからでも'@/...'でアクセスできるようになり絶対パスでモジュールのインポートを行うことが可能です。

おわりに

webpackでモジュールインポートのalias設定を実現しました。 ../がなくなり、utilコードなどへのアクセスが簡単になったので、個人的にかなり満足している設定です。