以下是手动拆分代码之前的相关代码:
import React from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import Protected from '../container-components/authentication/protected.js';
import LoginContainer from '../container-components/authentication/loginContainer.js';
import axios from 'axios';
import {Loader} from 'semantic-ui-react';
render(){
if(this.state.isLoading){
return(
<div>
<Loader style={{marginTop: '30vh'}} active inline='centered'/>
</div>
)
}
return(
<BrowserRouter>
<div>
<Switch>
<Route
path='/stream'
render={(props) =>
<Protected {...props}
isLoggedIn={this.state.isLoggedIn}
onLogout={this.handleLogout}
user={this.state.user}
/>
}
/>
<Route
path='*'
render={(props) =>
<LoginContainer {...props}
isLoggedIn={this.state.isLoggedIn}
onLogin={this.handleLogin}
/>
}
/>
</Switch>
</div>
</BrowserRouter>
)
这是代码拆分后的代码:
import React from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import LoginContainer from '../container-components/authentication/loginContainer.js';
import axios from 'axios';
import {Loader} from 'semantic-ui-react';
import Loadable from 'react-loadable';
const LoadableProtected = Loadable({
loader: () => import('../container-components/authentication/protected.js'),
loading: Loader,
render(loaded, props) {
let Component = loaded.default;
return <Component {...props} />
}
})
render(){
if(this.state.isLoading){
return(
<div>
<Loader style={{marginTop: '30vh'}} active inline='centered'/>
</div>
)
}
return(
<BrowserRouter>
<div>
<Switch>
<Route
path='/stream'
render={(props) =>
<LoadableProtected {...props}
isLoggedIn={this.state.isLoggedIn}
onLogout={this.handleLogout}
user={this.state.user}
/>
}
/>
<Route
path='*'
render={(props) =>
<LoginContainer {...props}
isLoggedIn={this.state.isLoggedIn}
onLogin={this.handleLogin}
/>
}
/>
</Switch>
</div>
</BrowserRouter>
)
}
我也在这里尝试了本教程:https://serverless-stack.com/chapters/code-splitting-in-create-react-app.html
这似乎与react-loadable正在做的一样。
我正在将webpack v4与弹出的create-react-app和以下babel软件包/插件一起使用:
“ @ babel / cli”:“ ^ 7.2.0” “ @ babel / plugin-proposal-class-properties”:“ ^ 7.2.1” “ @ babel / plugin-proposal-export-default-from”:“ ^ 7.2.0” “ @ babel / preset-env”:“ ^ 7.2.0” “橡子”:“ ^ 6.0.4” “ babel-eslint”:“ ^ 9.0.0” “ babel-plugin-动态导入节点”:“ ^ 2.2.0” “ babel-plugin-lodash”:“ ^ 3.3.4” “ babel-core”:“ ^ 6.26.3”, “ babel-jest”:“ 20.0.3”, “ babel-loader”:“ ^ 8.0.4”, “ babel-preset-react-app”:“ ^ 6.1.0”, “ babel-runtime”:“ *”,
这没什么大不了的,它并没有减小捆绑包的大小,我只是无法弄清楚为什么会这样。
答案 0 :(得分:0)
也许您可以尝试使用TerserPLugin来最小化JS?
optimization: {
minimizer: [new TerserPlugin({ /* additional options here */ })],
},