簡體   English   中英

Webpack和React getComponent()不會異步加載組件

[英]Webpack & React getComponent() not loading asynchronously component

我正在使用Webpack 3.7.1和React 15.6.1,並且試圖動態加載不同的組件。

我想做什么

  • 從代碼拆分時創建的不同Webpack塊異步加載組件

我做了什么

  • 使用getComponent()import()生成塊
  • 正確配置了webpack.config文件,以便創建塊(代碼拆分)

問題

  • 訪問路徑時會生成塊, 但未正確加載
  • getComponent()似乎不起作用

我的Webpack.config文件

module.exports = {
  devServer: {
    historyApiFallback: true
  },
  entry: {
    app:"./src/index.js",
    vendor: [
      "axios",
      "react",
      "react-dom",
      "react-redux",
      "react-router",
      "react-router-dom",
      "redux"
    ]
  },
  output: {
    path: __dirname + '/public/views',
    filename: '[name].js',
    chunkFilename: '[chunkhash].chunk.js',
    publicPath: "/views/"
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: "babel-loader",
        exclude: [/node_modules/, /pdfmake.js$/]
      },
      {
        test: /\.json$/,
        loader: "json-loader"
      }
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: "vendor",
      minChunks: Infinity
    }),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
      filename:  __dirname + "/views/index.ejs",
      template: __dirname + "/views/template.ejs",
      inject: 'body',
      chunks: ['vendor', 'app'],
      chunksSortMode: 'manual'
    }),
    new PreloadWebpackPlugin({
      rel: "preload",
      include: ["vendor", "app"]
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
  ]
};

我的index.js文件(我的應用程序的根目錄)

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import promise from "redux-promise";
import reducers from "./reducers";
import AppInit from "./containers/appInit";



import ProfRegisteringModal from "./containers/modals/register_prof_explanation_modal";

const createStoreWithMiddleware = applyMiddleware(promise)(createStore);

function errorLoading(err) {
  console.error("Dynamic page loading failed", err);
}

function loadRoute(cb) {
  return module => cb(null, module.default);
}

console.log("testst");

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <AppInit>
      <BrowserRouter>
        <div style={{ height: "100%" }}>
          <ProfRegisteringModal />
          <Switch>
            <Route
              path="/inscription/:user"
              getComponent={(location, callback) => {
                import(
                  "./components/registering/registering_landing_page.js"
                )
                  .then(loadRoute(cb))
                  .catch(errorLoading);
              }}
            />
            <Route
              path="/inscription"
              getComponent={(location, callback) => {
                import(
                  "./components/registering/registering_landing_page.js"
                )
                  .then(loadRoute(cb))
                  .catch(errorLoading);
              }}
            />
            <Route
              path="/connexion"
              getComponent={(location, callback) => {
                import("./containers/registering/signing_in.js")
                  .then(loadRoute(cb))
                  .catch(errorLoading);
              }}
            />
            <Route
              path="/equipe"
              getComponent={(location, callback) => {
                import("./components/team_pres.js")
                  .then(loadRoute(cb))
                  .catch(errorLoading);
              }}
            />
            <Route
              path="/"
              getComponent={(location, callback) => {
                import("./containers/app_container.js")
                  .then(loadRoute(cb))
                  .catch(errorLoading);
              }}
            />
          </Switch>
        </div>
      </BrowserRouter>
    </AppInit>
  </Provider>,
  document.querySelector(".root")
);

該文件已正確加載,因為我可以看到console.log(“ test”)出現在控制台中。

訪問任何路由時,沒有正確加載任何組件。

非常感謝您的幫助

我認為您的代碼缺失是觸發更新的一種方法。 我記得通過圍繞import()承諾創建包裝器來解決此問題。

// AsyncComponent.js

export default function wrapper(importComponent) {
  class AsyncComponent extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        Comp: null
      };
    }
    componentDidMount() {
      importComponent()
        .then(Comp => this.setState({
          Comp
        }))
        .catch(err => this.setState({
          error: err
        }));
    }
    render() {
      if(this.state.error) {
        return <h2> Loading error
            <button onClick={e => this.componentDidMount()}> Try again </button>
          </h2>
      }
      const Comp = this.state.Comp;
      return Comp ?
        <Comp {...this.props} /> :
        <div> Still Loading: You can add a spinner here </div>
    }
  }
  return AsyncComponent;
}


// Routes.js

import AsyncComponent from './component/AsyncComponent';

const Users   = AsyncComponent(() => import(/* webpackChunkName:"users"  */ './Users'))
const Home    = AsyncComponent(() => import(/* webpackChunkName:"home"   */ './Home'))
const Equipe  = AsyncComponent(() => import(/* webpackChunkName:"equipe" */ './Equipe'))


<Route path='/users' component={Users} />
<Route path='/equipe' component={Equipe} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM