-
-
Save jasdeepkhalsa/f39c0d5b0c2fedfb56d80891b28b4c56 to your computer and use it in GitHub Desktop.
React & Webpack Route-based code splitting example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; | |
import Loadable from 'react-loadable'; | |
const Loading = () => <div>Loading...</div>; | |
const Home = Loadable({ | |
loader: () => import('./routes/Home'), | |
loading: Loading, | |
}); | |
const About = Loadable({ | |
loader: () => import('./routes/About'), | |
loading: Loading, | |
}); | |
const App = () => ( | |
<Router> | |
<Switch> | |
<Route exact path="/" component={Home}/> | |
<Route path="/about" component={About}/> | |
</Switch> | |
</Router> | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
entry: { | |
main: './src/app.js', | |
}, | |
output: { | |
// `filename` provides a template for naming your bundles (remember to use `[name]`) | |
filename: '[name].bundle.js', | |
// `chunkFilename` provides a template for naming code-split bundles (optional) | |
chunkFilename: '[name].bundle.js', | |
// `path` is the folder where Webpack will place your bundles | |
path: './dist', | |
// `publicPath` is where Webpack will load your bundles from (optional) | |
publicPath: 'dist/' | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you’re setting up Webpack yourself, you’ll probably want to read Webpack’s guide on code splitting. Your Webpack config should look vaguely like this (above)
When using Babel, you’ll need to make sure that Babel can parse the dynamic import syntax but is not transforming it. For that you will need babel-plugin-syntax-dynamic-import.
Taken from: https://reactjs.org/docs/code-splitting.html#route-based-code-splitting
Under License: Creative Commons Attribution 4.0