profile
西村 祐真
@variant3a
SveltekitでKnex(Objection.js)を使うときに発生するエラー: 「__dirname is not defined in ES module scope」の解決策
calendar_today
2023-12-04
insights
views: 219
thumbnail images

問題

Objection.jsを利用したプロジェクトでSveltekitを使用し、ビルドした際に以下のようなエラーが出る。

__dirname is not defined in ES module scope

Objection.jsはKnexベースなので、どちらのORMを使用する際も問題が発生する可能性がある。

原因

これはSveltekitがESMで、KnexがCJSで定義している__dirnameを扱えないことが原因らしい。

詳細はここ: Svellte/SvelteKit tips集 - Zenn

対策

プロジェクトでは以下のように設定した。

import { DB_DATABASE, DB_HOST, DB_PASSWORD, DB_PORT, DB_USERNAME } from '$env/static/private'
import type { knex as InportedKnex } from 'knex'
import { createRequire } from 'module'

const require = createRequire(import.meta.url ?? __filename)
const { knex: RequiredKnex } = require('knex')
const Knex: typeof InportedKnex = RequiredKnex

export const knex = Knex({
    client: 'mysql2',
    useNullAsDefault: true,
    connection: {
        host: DB_HOST,
        port: Number(DB_PORT),
        user: DB_USERNAME,
        password: DB_PASSWORD,
        database: DB_DATABASE
    },
})
calendar_today
2023-12-04
insights
views: 219