Material UI:元素类型无效:应为字符串(对于内置组件)或 class/function(对于复合组件)但得到:空

Material UI: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: null

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: null. Check the render method of TransitionGroup.

具体来说,只有当我使用 material-ui 并导入它的任何组件时才会出现此问题。我无法提供重现它的具体步骤,因为它似乎是一个 webpack 配置或一个 babel 配置,而且这是一个非常通用的配置。此外,还有很多其他人已经遇到过这个问题,我已经尝试了很多解决方案但都没有成功。这就是为什么我决定也许堆栈溢出社区可以提供一些启示。

所以首先,我 100% 准确地认为问题是使用@material-ui。在我的项目中,我尝试像这样 Button 导入

import Button from '@material-ui/core/Button'

并像这样使用它:

<Button
        onClick={()=>{}}
        size='small'
        variant='outlined'
        color='secondary'
        className='primary-button'>
 This is a Button
</Button>

此外,我已经尝试过不同的导入,例如 import { Button } from '@material-ui/core'。所以第一级和第二级导入。第三级已经不行了。没有成功!请注意,删除 Button 将 100% 有效。所以我猜测这可能是来自 babel 或 webpack 的配置问题。所以我玩了很多,研究了很多,但仍然没有成功!

这是我现在的 webpack.config

/**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path')
const webpack = require('webpack')
const LoadableWebpackPlugin = require('@loadable/webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const merge = require('webpack-merge')

module.exports = options => (merge.smart({
  bail: true,
  output: {
    path: path.resolve(process.cwd(), 'build'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.(eot|otf|ttf|woff|woff2)$/,
        use: 'file-loader'
      },
      {
        test: /\.svg$/,
        use: [
          {
            loader: 'svg-url-loader',
            options: {
              // Inline files smaller than 10 kB
              limit: 10 * 1024,
              noquotes: true
            }
          }
        ]
      },
      {
        test: /\.(jpg|png|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              // Inline files smaller than 10 kB
              limit: 10 * 1024
            }
          },
          {
            loader: 'image-webpack-loader',
            options: {
              mozjpeg: {
                enabled: false
                // NOTE: mozjpeg is disabled as it causes errors in some Linux environments
                // Try enabling it in your environment by switching the config to:
                // enabled: true,
                // progressive: true,
              },
              gifsicle: {
                interlaced: false
              },
              optipng: {
                optimizationLevel: 7
              },
              pngquant: {
                quality: '65-90',
                speed: 4
              }
            }
          }
        ]
      },
      {
        test: /\.(mp4|webm)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000
          }
        }
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(['build'], {
      root: process.cwd(),
      verbose: true,
      dry: false
    }),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new LoadableWebpackPlugin({ writeToDisk: true })
  ],
  resolve: {
    modules: [
      path.join(process.cwd(), 'sass'),
      path.join(process.cwd(), 'node_modules'),
      path.join(process.cwd(), 'src')
    ],
    extensions: ['.json', '.js']
  },
  target: 'web' // Make web variables accessible to webpack, e.g. window
}, options))

这是我现在的 babel.config.js

function isWebTarget(caller) {
  return Boolean(caller && caller.target === 'web')
}

module.exports = (api) => {
  const web = api.caller(isWebTarget)
  return {
    presets: [
      [
        '@babel/preset-env',
        {
          loose: true,
          targets: !web ? { node: 'current' } : {
            esmodules: true
          },
          modules: 'commonjs'
        }
      ],
      '@babel/preset-react'
    ],
    plugins: [
      '@babel/plugin-syntax-dynamic-import',
      '@babel/plugin-proposal-function-bind',
      ['@babel/plugin-proposal-decorators', { legacy: true }],
      ['@babel/plugin-proposal-class-properties', { loose: true }],
      ['babel-plugin-import', {
        libraryName: '@material-ui/core'
      }, 'core'],
      ['babel-plugin-import', {
        libraryName: '@material-ui/icons'
      }, 'icons'],
      [
        'transform-imports',
        {
          '@material-ui/core': {
            // Use "transform: '@material-ui/core/${member}'," if your bundler does not support ES modules
            'transform': '@material-ui/core/${member}',
            'preventFullImport': true
          },
          '@material-ui/icons': {
            // Use "transform: '@material-ui/icons/${member}'," if your bundler does not support ES modules
            'transform': '@material-ui/icons/${member}',
            'preventFullImport': true
          }
        }
      ],
      '@babel/plugin-transform-async-to-generator',
      '@babel/plugin-proposal-object-rest-spread',
      '@loadable/babel-plugin',
      web && 'react-hot-loader/babel'
    ].filter(Boolean)
  }
}

唯一让我印象深刻的是您在第一个预设中使用“commonjs”配置了 babel。尝试将其更改为 'auto' 或 es6 模块。

不同之处在于,在 commonjs 中,您应该使用 const a = require('some-module')

导入

在 es6 中是:import a from 'some-module'

您可以通过将导入更改为:

来测试是否属于这种情况

const Button = require('@material-ui/core/Button')

const Button = require('@material-ui/core/Button').default

如果可行,请尝试从第一个预设中删除“模块”或将其更改为“自动” https://babeljs.io/docs/en/babel-preset-env#modules

我能够在 webpack.config

上解决这个问题

对于可能遇到同样问题的其他人,在我的webpack.config

发件人:

 resolve: {
    modules: [
      path.join(process.cwd(), 'sass'),
      path.join(process.cwd(), 'node_modules'),
      path.join(process.cwd(), 'src')
    ]
}

收件人:

resolve: {
    modules: [
      path.join(process.cwd(), 'sass'),
      'node_modules',
      path.join(process.cwd(), 'src')
    ]
}

注意 node_modules 上的部分,您只需删除 path.join 或任何路径解析。整个周末我一直在努力解决这个问题,我只需要换一条线。 (典型的开发人员生活)。顺便说一句,甚至不是这个问题让我想到了这个解决方案。所以像 can't resolve dom-helpers 和其他多个库版本与子模块冲突,如果你使用 webpack,你需要检查你的 webpack 模块分辨率。