Я пытаюсь создать API для firestore - один модуль, который будет работать в браузере и на node-js одинаково.
Так что я заглянул в подчеркивание, чтобы попытаться выяснить, как онивыполнил это, и я нашел половину решения, но я все еще получаю некоторые ошибки в среде браузера для импорта firebase
Я получаю ошибку "require" is not a function
, хотя в других местах, которые я использую, требуются запускиотлично - все скомпилировано с помощью веб-пакета.
Итак, у меня есть 2 файла инициализации:
- firebase-admin init (для среды node-js)
-
const admin = require('firebase-admin')
const key = require("/path/to/sa.json")
const settings = { timestampsInSnapshots: true }
const app = admin.initializeApp({
credential: admin.credential.cert(key),
databaseURL: `https://${ key.project_id }.firebaseio.com`
})
const Firestore = app.firestore()
Firestore.settings(settings)
module.exports.app = app
module.exports = Firestore
firestore-client init (для среды браузера)
-
const firebase = require('firebase/app')
require('firebase/firestore')
require('firebase/auth')
const settings = { timestampsInSnapshots: true }
const config = {
apiKey: "xxxxx",
authDomain: "xxxxxx",
databaseURL: "xxxxx",
projectId: "xxxxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxx"
}
const Firestore = firebase.firestore()
Firestore.settings(settings)
module.exports.app = !firebase.apps.length ? firebase.initializeApp(config) : firebase.app() // eslint-disable-line no-negated-condition
module.exports.Auth = firebase.auth()
module.exports = Firestore
Это моя точка входа для API
((function() {
const root = this
var api = {}
if (typeof window === 'undefined') {
// this works
api.fs = require('./services/firebase-admin-init')
module.exports = api
root.api = api
} else {
// this require fails because of the require('firebase/app') inside the firebase-client init
api.fs = require('./services/firebase-client-init')
root.api = api
}
// this require works
api.organization = new (require('./organization'))(api.fs)
})())
иэто мой webpack.conf.js
const path = require('path')
const TerserPlugin = require('terser-webpack-plugin')
const nodeExternals = require('webpack-node-externals')
module.exports = {
entry: './src/index.js',
mode: 'production',
target: 'web',
externals: [nodeExternals()],
node: {
child_process: 'empty',
fs: 'empty',
http2: 'empty',
net: 'empty',
tls: 'empty',
},
output: {
filename: 'api.js',
path: path.resolve(__dirname, 'dist')
},
optimization: {
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
// mangle: false,
keep_fnames: true,
keep_classnames: true,
compress: {
keep_fnames: true,
keep_classnames: true,
},
},
})
]
}
}
Любые идеи о том, как заставить это работать?