Skip to content

webpack遇到的一些问题(2)

xiaohesong edited this page Nov 30, 2017 · 3 revisions

这里接着阐述我遇到的问题.这节主要说的是关于配置按需加载遇到的问题

  • AsyncComponent.js
import React, {Component} from "react";

export default function asyncComponent(importComponent) {
  class AsyncComponent extends Component {
    constructor(props) {
      super(props);

      this.state = {
        component: null
      };
    }

    async componentDidMount() {
      const {default: component} = await importComponent();

      this.setState({component: component});
    }

    render() {
      const Component = this.state.component;

      return Component
        ? <Component {...this.props}/>
        : null;
    }
  }

  return AsyncComponent;
}
  1. Home.js
import React from 'react'
const Home = () => {
  return (<h1>It's My Home</h1>)
}

export default Home
  1. Menu.js
import React from 'react'
import {Menu, Icon} from 'antd';
import {Link} from 'react-router-dom'
import asyncComponent from './AsyncComponent';

const AsyncHome = asyncComponent(() => import("./Home"))
const SubMenu = Menu.SubMenu;

class MyMenu extends React.Component {
  render() {
    return (
      <Router>
        <Route path="/" component={AsyncHome} />
        <Menu theme="dark" defaultSelectedKeys={['1']} mode="inline">
          <Menu.Item key="2">
            <Icon type="desktop"/>
            <Link to="/">
              <span>Option 2</span>
            </Link>
         </Menu.Item>
        </Menu>
      </Router>
    )
  }
}

export default MyMenu

预期的结果,这样应该是可以的.可是对于一些es6语法,webpack还是需要配置一番.所以碰到了问题.

遇到的问题

  1. Uncaught ReferenceError: regeneratorRuntime is not defined

解决方法: 引入transform-runtime.

包的地址

transform-runtime与babel-polyfill的区别

  1. Uncaught ReferenceError: webpackJsonp is not defined

解决方法: 引入CommonsChunkPlugin

custom-react源码