首页 > 解决方案 > Material UI:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到: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'. 所以第一级和第二级进口。3级已经不行了。没有成功!请注意,删除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)
  }
}

标签: webpackmaterial-uibabeljs

解决方案


唯一让我印象深刻的是,您在第一个预设中使用“commonjs”配置了 babel。尝试将其更改为“自动”或 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


推荐阅读