API Firestore для браузера и узла - PullRequest
0 голосов
/ 30 декабря 2018

Я пытаюсь создать API для firestore - один модуль, который будет работать в браузере и на node-js одинаково.

Так что я заглянул в подчеркивание, чтобы попытаться выяснить, как онивыполнил это, и я нашел половину решения, но я все еще получаю некоторые ошибки в среде браузера для импорта firebase

Я получаю ошибку "require" is not a function, хотя в других местах, которые я использую, требуются запускиотлично - все скомпилировано с помощью веб-пакета.

Итак, у меня есть 2 файла инициализации:

  1. 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,
          },
        },
      })
    ]
  }
}

Любые идеи о том, как заставить это работать?

1 Ответ

0 голосов
/ 31 декабря 2018

Попробуйте что-то похожее на этот стиль:

((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


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)

api.app = !firebase.apps.length ? firebase.initializeApp(config) : firebase.app() 

api.auth = firebase.auth()
api.fs = Firestore
root.api = api
}

// this require works
api.organization = new (require('./organization'))(api.fs)

})())

Надеюсь, эта помощь.с новым годом!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...