首页 > 解决方案 > 汇总错误:导入 Material-UI 组件时无法从 @babel/runtime 加载模块

问题描述

我正在尝试index.js使用汇总编译此文件:

import React from "react";
import ReactDOM from "react-dom";
import Grid from "@material-ui/core/Grid";

ReactDOM.render(
    <React.StrictMode>
        <Grid container>
        </Grid>
    </React.StrictMode>,
    document.getElementById('root')
);

rollup.config.js

import { nodeResolve } from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';

export default {
    input: 'index.js',
    output: {
        file: 'dist/bundle.js',
        format: 'iife'
    },
    plugins: [
        nodeResolve(),
        babel({ babelHelpers: 'bundled', exclude: /node_modules/ }),
        commonjs(),
    ],
};

babel.config.json

{
    "presets": [
        "@babel/preset-react",
        "@babel/preset-env"
    ]
}

现在,当我运行时出现npx rollup -c此错误:

[!] 错误:无法加载 /home/recursive-beast/Desktop/repositories/myproject/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties(由 node_modules/@material-ui/core/esm/Grid/Grid 导入.js): ENOENT: 没有这样的文件或目录,打开 '/home/recursive-beast/Desktop/repositories/myproject/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties'

这是出乎意料的,因为@babel/runtime它是 的依赖项@material-ui/core,并且我已经检查过它是否安装在 node_modules 文件夹中。

从昨天开始,我一直在尝试找出解决方案,但没有成功,那么问题的根源是什么?

标签: javascriptreactjsmaterial-uirollupjs

解决方案


我找到了一个可行的解决方案。

我只是添加@rollup/plugin-alias插件

... //other code
const alias = require('@rollup/plugin-alias');

module.exports = [
  {
    ... // other config
    plugins: [
      alias({
        entries: [
          { find: '@ui/lab', replacement: '@material-ui/lab/esm' },
          { find: '@ui/core', replacement: '@material-ui/core/esm' },
          { find: '@ui/icons', replacement: '@material-ui/icons/esm' },
          { find: /^@babel\/runtime\/helpers\/(.*)$/, replacement: '@babel/runtime/helpers/$1.js' }
        ]
      }),
      ...// other plugins
    ],
  },
]

@material-ui在js文件中使用

import Alert from '@ui/lab/Alert'

import AppBar from '@ui/core/AppBar'
import Toolbar from '@ui/core/Toolbar'
import Grid from '@ui/core/Grid'
import Paper from '@ui/core/Paper'
import Container from '@ui/core/Container'

import PlayIcon from '@ui/icons/PlayArrow'

import {
  createMuiTheme,
  ThemeProvider,
  makeStyles,
  createStyles
} from '@ui/core/styles'

import red from '@ui/core/colors/red'


... // other code

以上,希望对你有帮助。


推荐阅读