Laravel Mix Hot Module Reloading With React
Interested in a boilerplate with HMR included amongst React Router, Typescript support and more?
- Ensure you have the relevant npm dependencies
Note we are using webpack-dev-server v2 and webpack v3. This is as webpack dev server v2 is for webpack 3, webpack-dev-server v3 is for webpack 4 and so on. Confusing, right?
npm install -D webpack@3.*
npm install -D webpack-dev-server@2.*
- Configure Webpack
In webpack.mix add this code to the bottom:
mix.webpackConfig({output: {publicPath: "https://localhost:8080/"},devServer: {hot: true, // this enables hot reloadinline: true, // use inline method for hmrcontentBase: path.join(__dirname, "public"),https: true, //trueport: 8080,headers: { "Access-Control-Allow-Origin": "*" },watchOptions: {exclude: [/bower_components/, /node_modules/]}},node: {fs: "empty",module: "empty"},});// Per this issue: https://github.com/JeffreyWay/laravel-mix/issues/1483
Mix.listen("configReady", webpackConfig => {if (Mix.isUsing("hmr")) {// Remove leading '/' from entry keyswebpackConfig.entry = Object.keys(webpackConfig.entry).reduce((entries, entry) => {entries[entry.replace(/^\//, "")] = webpackConfig.entry[entry];// }console.log(entries);return entries;},{});// Remove leading '/' from ExtractTextPlugin instanceswebpackConfig.plugins.forEach(plugin => {if (plugin.constructor.name === "ExtractTextPlugin") {console.log(plugin.filename);plugin.filename = plugin.filename.replace(/^\//, "");console.log(plugin.filename);}});}});
2. Install react-hot-loading
npm install -D react-hot-loader
3. Add this to the top of your app.js
import { AppContainer } from 'react-hot-loader'
4. Enclose your main App component with the AppContainer component
How mine looks using Redux & React Router
Here I am using redux and so my main Router/App component is wrapped in a Provider
5. Enable Hot Module Reloading
At the bottom of your App.js file that we have been editing add this:
if (process.env.NODE_ENV === 'development' && module.hot) {module.hot.accept();}
6. Run Laravel mix with Hot Module Reloading
Try these until one works:npm run hmrornpm run hotorcross-env NODE_ENV=development webpack-dev-server --inline --hotorNODE_ENV=development webpack-dev-server --inline --hot
Found this article helpful?
Follow me on Medium and Twitter for more.
I’m also available to hire 👍 grmcameron@gmail.com