【问题标题】:Navigator undefined on React Typescript Firebase project在 React Typescript Firebase 项目上未定义导航器
【发布时间】:2018-12-03 06:26:31
【问题描述】:

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

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

这是我的 webpack 配置:(来自this 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'
  }
};

只要在我的应用程序中包含 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;

无论我做什么,我都会收到导航错误。即使我不导出身份验证对象。据我所知,它与 babel-loader 根据 SO question 添加严格模式有关,我想?所有其他相关搜索似乎都与 firebase-ui 有关,我没有以任何方式使用它。

但我不知道他是如何关闭严格模式的,更不用说 OP 没有使用 typescript,我在这种情况下使用的是 ts-loader。我无法为我的生活弄清楚如何让它工作。除了所有这些,如果我尝试使用 auth() 的 firebase 对象,例如,我会从 webpack 收到一堆关于 firebase 对象上不存在 auth 的警告。完全被难住了。

【问题讨论】:

    标签: javascript reactjs typescript firebase webpack


    【解决方案1】:

    所以万一其他人遇到这个问题。看来这是一个包版本问题。我假设我使用的 boilerplate 中特别包含的软件包版本不能很好地与 firebase 配合使用。

    我更新了typescriptreact-hot-loader,很可能是问题webpack 从版本3.0.4 更新到4.12.1,现在看来一切正常。此外,随着更新,我现在像这样导入 firebase:

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

    希望这对某人有所帮助。

    【讨论】:

      【解决方案2】:

      在我的例子中,我修复了这个导入函数

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

      【讨论】:

        猜你喜欢
        • 2017-05-02
        • 2021-09-10
        • 1970-01-01
        • 1970-01-01
        • 2017-09-29
        • 2021-04-24
        • 1970-01-01
        • 2018-01-07
        • 2019-07-07
        相关资源
        最近更新 更多