我正在使用 Webpack 3.7.1 和 React 15.6.1,我正在尝试动态加载不同的组件。
我想做什么
- 从代码拆分时创建的不同 block webpack 异步加载组件
我做了什么
- 使用getComponent() 和import() 生成 block
- 正确配置 webpack.config 文件以便创建 block (代码拆分)
问题
- block 在访问路由时生成但未加载正确
- 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 文件(我的 React 应用程序的根目录)
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")
);
此文件 index.js 已正确加载,因为我可以看到 console.log("test") 出现在我的控制台中。
访问任何路由时都没有正确加载任何组件。
非常感谢您的帮助
更新
一定要有 Babel-polyfill!!我是这样解决的
最佳答案
您的 webpack.config 文件似乎没问题。我所做的工作是在
中创建异步组件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 C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
return AsyncComponent;
}
然后使用如下
const RegisterPage = asyncComponent(() => import("./components/registering/registering_landing_page.js"));
我认为 Route 没有 getComponent
属性,但我可能错了。您的 Route 语句应如下所示。
<Route
path="/register"
render: props => <RegisterPage {...props} />
/>
关于javascript - Webpack & React getComponent() 不加载组件(异步),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48301875/