简体   繁体   English

在 React Typescript Firebase 项目上未定义导航器

[英]Navigator undefined on React Typescript Firebase project

I've been googling for a couple hours now and can't seem to resolve my issue.我已经用谷歌搜索了几个小时,似乎无法解决我的问题。

I have a webpack/React/Typescript/Mobx setup and am attempting to use firebase.我有一个 webpack/React/Typescript/Mobx 设置并且正在尝试使用 firebase。

Here is my webpack config: (boilerplate from this repo)这是我的 webpack 配置:(来自 这个repo 的样板)

var webpack = require('webpack');
var path = require('path');

// variables
var isProduction = process.argv.indexOf('-p') >= 0;
var sourcePath = path.join(__dirname, './src');
var outPath = path.join(__dirname, './dist');

// plugins
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var WebpackCleanupPlugin = require('webpack-cleanup-plugin');

module.exports = {
  context: sourcePath,
  entry: {
    main: './main.tsx'
  },
  output: {
    path: outPath,
    filename: 'bundle.js',
    chunkFilename: '[chunkhash].js',
    publicPath: '/'
  },
  target: 'web',
  resolve: {
    extensions: ['.js', '.ts', '.tsx'],
    // Fix webpack's default behavior to not load packages with jsnext:main module
    // (jsnext:main directs not usually distributable es6 format, but es6 sources)
    mainFields: ['module', 'browser', 'main'],
    alias: {
      app: path.resolve(__dirname, 'src/app/'),
      assets: path.resolve(__dirname, 'src/assets/')
    }
  },
  module: {
    rules: [
      // .ts, .tsx
      {
        test: /\.tsx?$/,
        use: [
          isProduction
            ? 'ts-loader'
            : {
                loader: 'babel-loader',
                options: {
                  babelrc: false,
                  plugins: ['react-hot-loader/babel']
                }
              },
          'ts-loader'
        ],
        // : ['babel-loader?plugins=react-hot-loader/babel&presets=', 'ts-loader'],
        exclude: /node_modules/
      },
      // css
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'css-loader',
              query: {
                modules: true,
                sourceMap: !isProduction,
                importLoaders: 1,
                localIdentName: '[local]__[hash:base64:5]'
              }
            },
            {
              loader: 'postcss-loader',
              options: {
                ident: 'postcss',
                plugins: [
                  require('postcss-import')({ addDependencyTo: webpack }),
                  require('postcss-url')(),
                  require('postcss-cssnext')(),
                  require('postcss-reporter')(),
                  require('postcss-browser-reporter')({
                    disabled: isProduction
                  })
                ]
              }
            }
          ]
        })
      },
      {
        test: /\.css$/,
        include: /node_modules/,
        use: ['style-loader', 'css-loader']
      },
      // static assets
      { test: /\.html$/, use: 'html-loader' },
      { test: /\.(png|jpg)$/, use: 'url-loader?limit=10000' },
      { test: /\.webm$/, use: 'file-loader' }
    ]
  },
  optimization: {
    splitChunks: {
      name: true,
      cacheGroups: {
        commons: {
          chunks: 'initial',
          minChunks: 2
        },
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          chunks: 'all',
          priority: -10
        }
      }
    },
    runtimeChunk: true
  },
  plugins: [
    new WebpackCleanupPlugin(),
    new ExtractTextPlugin({
      filename: 'styles.css',
      disable: !isProduction
    }),
    new HtmlWebpackPlugin({
      template: 'assets/index.html'
    })
  ],
  devServer: {
    contentBase: sourcePath,
    hot: true,
    inline: true,
    historyApiFallback: {
      disableDotRule: true
    },
    stats: 'minimal'
  },
  devtool: 'cheap-module-eval-source-map',
  node: {
    // workaround for webpack-dev-server issue
    // https://github.com/webpack/webpack-dev-server/issues/60#issuecomment-103411179
    fs: 'empty',
    net: 'empty'
  }
};

Just by including firebase in my app i relentlessly end up with this error:仅仅通过在我的应用程序中包含 firebase,我就会不断地遇到这个错误:

Uncaught TypeError: Cannot read property 'navigator' of undefined    auth.esm.js?69b5:10 

I have tested by including a simple component like so:我已经通过包含一个简单的组件进行了测试,如下所示:

import * as React from 'react';
import * as Styles from './styles.css';
import 'app/utils/FirebaseUtil';

interface TestProps {}

export const Test: React.StatelessComponent<TestProps > = () => (
    <div className={Styles.root}>
        {'Hello World'}
    </div>
);

FirebaseUtil: FirebaseUtil:

import * as firebase from 'firebase';

const config = {
  apiKey: '**my key here**',
  authDomain: '** my domain here **'
};

firebase.initializeApp(config);

export const fbAuth = firebase.auth;

No matter what I seem to do I get the navigator error.无论我似乎做什么,我都会收到导航器错误。 Even if i dont export the auth object.即使我不导出 auth 对象。 As far as I can tell its related to babel-loader adding strict-mode according to this SO question , i think?据我所知,它与根据这个SO 问题添加严格模式的 babel-loader 相关,我想? All other related searches seem to have to do with firebase-ui, which i am not using in any way.所有其他相关搜索似乎都与 firebase-ui 有关,我没有以任何方式使用它。

But I have no idea how he manages to turn off strict mode, not to mention the OP is not using typescript and I am using ts-loader in this case.但我不知道他是如何设法关闭严格模式的,更不用说 OP 没有使用打字稿,在这种情况下我使用的是 ts-loader。 I can't for the life of me figure out how to get it working.我一生都无法弄清楚如何让它发挥作用。 Aside from all of this if I do try use the firebase object for auth() for example I get a bunch of warnings from webpack about auth not existing on the firebase object.除了所有这些,如果我尝试将 firebase 对象用于 auth() 例如,我会从 webpack 收到一堆关于 firebase 对象上不存在 auth 的警告。 Totally stumped.完全被难住了。

So in case anyone else runs into this problem.所以万一其他人遇到这个问题。 It appears it was a package version issue.看来是包版本问题。 Im assuming that the package versions specifically included in the boilerplate i used didn't play well with firebase.我假设我使用的 样板文件中特别包含的软件包版本与 firebase 不兼容。

I updated typescript , react-hot-loader , and most likely the issue webpack from version 3.0.4 to 4.12.1 and things seem to be working ok now.我更新了typescriptreact-hot-loader和最有可能的问题webpack3.0.44.12.1版本,现在看起来一切正常。 Also with the updates I now import firebase like so:还有更新,我现在像这样导入 firebase:

import firebase from '@firebase/app';
import '@firebase/auth';

Hope this helps someone.希望这可以帮助某人。

In my case I fixed this importing functions在我的情况下,我修复了这个导入功能

import firebase from 'firebase/app'
import 'firebase/functions'
import 'firebase/analytics'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM