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

时间:2018-06-24 13:55:45

标签: javascript reactjs typescript firebase webpack

我已经搜索了两个小时,但似乎无法解决我的问题。

我有一个webpack / React / Typescript / Mobx设置,并且正在尝试使用Firebase。

这是我的webpack配置:(this回购中的样板)

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'
  }
};

只要在我的应用程序中包含firebase,我就会无休止地出现以下错误:

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

我已经通过添加一个像这样的简单组件进行了测试:

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:

import * as firebase from 'firebase';

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

firebase.initializeApp(config);

export const fbAuth = firebase.auth;

无论我做什么,都会出现导航器错误。即使我不导出auth对象。据我所知,它与根据此SO question添加严格模式的babel-loader有关,我认为呢?所有其他相关搜索似乎都与firebase-ui有关,我没有以任何方式使用它。

但是我不知道他如何设法关闭严格模式,更不用说OP没有使用打字稿,在这种情况下我正在使用ts-loader。我一辈子都无法弄清楚如何使它正常工作。除了所有这些以外,如果我确实尝试将firebase对象用于auth(),例如,我从webpack中收到了一堆关于firebase对象上不存在auth的警告。完全不知所措。

2 个答案:

答案 0 :(得分:0)

以防万一其他人遇到这个问题。看来这是软件包版本问题。我以为我专门使用的boilerplate中包含的软件包版本在firebase中不能很好地发挥作用。

我将typescriptreact-hot-loaderwebpack的版本从3.0.4更新到了4.12.1,现在看来一切正常。同样,通过更新,我现在也可以像这样导入firebase:

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

希望这对某人有帮助。

答案 1 :(得分:0)

就我而言,我修复了此导入功能

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