React lazy loading ChunklLoadError on webpack production build - reactjs

I'm using React lazy loading in order to dynamically load my components and some antd icons.
It is working perfectly in development environment. But I have some ChunkLoadError on my page when it is trying to load components. However, it is working fine when I remove all lazy loading.
Here code example:
const ProtectedRoute = lazy(() => import('./ProtectedRoute'));
const Login = lazy(() => import('../examples/AnimatedLoginForm'));
const Home = lazy(() => import('./Home'));
const Account = lazy(() => import('./Account'));
const Router = () => {
return (
<BrowserRouter>
<MainLayout>
<Suspense fallback={<Spinner />}>
<Switch>
<Route exact path="/login" component={Login} />
<ProtectedRoute exact path="/" component={Test} />
<ProtectedRoute path="/form" component={Home} />
<ProtectedRoute path="/settings" component={Settings} />
<ProtectedRoute path="/account" component={Account} />
</Switch>
</Suspense>
</MainLayout>
</BrowserRouter>
);
};
And there my webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const dotenv = require('dotenv');
const fs = require('fs');
const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');
module.exports = ({ ENVIRONMENT }) => {
// Get the root path (assuming your webpack config is in the root of your project!)
const currentPath = path.join(__dirname);
// Create the fallback path (the production .env)
const basePath = `${currentPath}/.env`;
// We're concatenating the environment name to our filename to specify the correct env file!
const envPath = `${basePath}.${ENVIRONMENT}`;
// Check if the file exists, otherwise fall back to the production .env
const finalPath = fs.existsSync(envPath) ? envPath : basePath;
// Set the path parameter in the dotenv config
const fileEnv = dotenv.config({ path: finalPath }).parsed;
// Reduce it to a nice object, the same as before (but with the variables from the file)
const envKeys = fileEnv
? Object.keys(fileEnv).reduce((prev, next) => {
const state = prev;
state[`process.env.${next}`] = JSON.stringify(fileEnv[next]);
return state;
}, {})
: {};
return {
entry: { app: './src/index.jsx' },
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: [
[
'import',
{ libraryName: 'antd', libraryDirectory: 'es', style: true }
]
]
}
},
{
// CSS imports
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.less$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{
loader: 'less-loader',
options: {
modifyVars: {},
javascriptEnabled: true
}
}
]
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'babel-loader'
},
{
loader: '#svgr/webpack',
options: {
babel: false,
icon: true
}
}
]
},
{
// Images imports
test: /\.(png|jpg|gif)$/,
use: ['file-loader']
},
{
// Fonts imports
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
}
]
},
resolve: { extensions: ['*', '.js', '.jsx'] },
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/',
filename: '[name].bundle.js'
},
devServer: {
contentBase: path.join(__dirname, 'public/'),
port: 3000,
publicPath: 'http://localhost:3000/dist/',
historyApiFallback: true,
hotOnly: true
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin(envKeys),
new AntdDayjsWebpackPlugin()
]
};
};
And my .babelrc
{
"presets": [
"#babel/env",
"#babel/preset-react"
],
"plugins": [
"syntax-dynamic-import"
]
}
I tried many many things, nothing worked, please help me.

Related

React webpack showing blank page on refresh

I am serving my static files from express and i can see that it loads index.html
But the problem is when on a rout for example localhost:8080/users and i refresh the page, the .css and main.js does not seam to be loaded so it returns blank page.. Any idea on what night be the problem?
My app.js
function App (){
return (
<div className="wrapper">
<Routes>
{routes.map(({ path, name, Component }, key) => (
<Route exact path={path} key={key} element={Component} />
))}
</Routes>
</div>
);
}
export default App
My index.js:
ReactDOM.render(
<Provider store={store}>
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path="*" element={<App />} />
</Routes>
</BrowserRouter>
</React.StrictMode>
</Provider>,
document.getElementById('root')
);
This is my webpack:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const Dotenv = require('dotenv-webpack');
const webpack = require('webpack');
require('dotenv').config({path:__dirname+'/../.env'})
module.exports = {
entry: {
app: path.join(__dirname, "/src/Index.js"),
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "main.js",
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
exclude: /node_modules/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
},
{
test: /\.css$/,
use: 'style-loader!css-loader'
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: "babel-loader",
},
{
test: /\.html$/,
exclude: /node_modules/,
use: "html-loader",
},
],
},
resolve: {
extensions: [".js", ".jsx"],
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
APP_API_URL : JSON.stringify(process.env.APP_API_URL)
},
}),
new Dotenv(),
new HtmlWebpackPlugin({
filename: "index.html",
template: "./src/index.html",
}),
new MiniCssExtractPlugin({
filename: "app.css",
chunkFilename: "[id].css",
}),
],
devServer: {
historyApiFallback: true,
contentBase: path.join(__dirname, "dist"),
compress: true,
port: process.env.PORT_CLIENT,
open: true,
stats: "errors-only",
}
};
Check out this finished example using React Router and compare it with your App.
https://stackblitz.com/edit/github-agqlf5?file=src%2Fmain.jsx

Lazy loading react-router-dom, webpack not working

I try to lazy load routes using react-router-dom but it doesn't work. Webpack should automatically split chunks on import() but it doesn't, I always end up with one main.hash.js file instead of multiple chunks.
Is there something I'm missing ?
App Component:
import * as React from 'react';
import { Route, BrowserRouter, Link } from 'react-router-dom';
const Todos = React.lazy(() => import('routes/Todos'))
class App extends React.Component<{}, {}> {
render() {
return (
<>
<BrowserRouter>
<React.Suspense fallback={<div>loading...</div>}>
<Route exact path="/" render={() => <Link to="/todos">Todos</Link>} />
<Route exact path="/todos" component={Todos} />
</React.Suspense>
</BrowserRouter>
</>
)
}
}
export default App;
Here is the webpack config in case it may be related to some plugins or missing config on this side:
webpack common config:
const webpack = require('webpack');
const HtmlWebPackPlugin = require('html-webpack-plugin');
// clean folder (dist in this case)
const CleanWebpackPlugin = require('clean-webpack-plugin');
// copy files
const CopyPlugin = require('copy-webpack-plugin');
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src', 'index.tsx'),
resolve: {
extensions: ['.js', '.ts', '.tsx', '.scss'],
alias: {
'src': path.resolve(__dirname, 'src/'),
'components': path.resolve(__dirname, 'src/components/'),
'routes': path.resolve(__dirname, 'src/routes/'),
}
},
plugins: [
new CleanWebpackPlugin(['dist'], {}),
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "index.html"
}),
new CopyPlugin([
{ from: 'assets', to: 'assets' },
]),
]
};
webpack prod config:
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const path = require('path');
// split css per js file
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// optimize js
const TerserPlugin = require('terser-webpack-plugin');
// optimize css
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// service-worker
const Workbox = require('workbox-webpack-plugin');
module.exports = merge(common, {
mode: 'production',
module: {
rules: [
{
test: /\.ts|\.tsx$/,
loader: "ts-loader",
include: path.resolve(__dirname, 'src')
},
{
test: /\.scss$/,
loader: MiniCssExtractPlugin.loader
},
{
test: /\.scss$/,
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[hash:base64:5]'
}
},
{
test: /\.scss$/,
loader: 'postcss-loader',
},
{
test: /\.scss$/,
loader: 'sass-loader',
}
],
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css',
}),
new OptimizeCssAssetsPlugin({}),
new Workbox.GenerateSW({
clientsClaim: true,
skipWaiting: true,
exclude: [/\.(?:png|jpg|jpeg|svg)$/],
runtimeCaching: [
{
urlPattern: /https?:\/\/.+/,
handler: 'StaleWhileRevalidate',
options: {
cacheableResponse: {
statuses: [0, 200]
}
}
}, {
urlPattern: /\.(?:png|jpg|jpeg|svg)$/,
handler: 'CacheFirst',
}],
})
],
optimization: {
minimizer: [new TerserPlugin()],
},
output: {
filename: '[name].[contenthash].js',
chunkFilename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist')
}
});
From: https://github.com/webpack/webpack/issues/5703#issuecomment-357512412
compilerOptions.module has to be set to esnext in order for webpack to split dynamic imports.

Rendering UI in React Router 4

I am still fairly new to ReactJS especially the routing portion of it. I have a couple of questions which I tried many solutions i found on stackoverflow but nothing seems to be helping me:
When i start my react project locally, i get localhost:3000. What if I want it to be shown as localhost:3000/extension/?
When i navigate about my project i can render the different pages. However, if i enter the URL directly into the browser, a blank page is rendered. There is no error. I read somewhere saying that my components are not connected to my routes. I am not sure what I need to do to correct it.
How can i ensure history is properly being utilized?
routes.js:
const RouteList = () => (
<Switch>
<Route path="/extension/" exact component={withRouter(HomePage)} />
<Route path="/extension/something" exact component={withRouter(SomethingPage)} />
<Route component={Error} />
</Switch>
);
App.js:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render () {
return (
<Router history={browserHistory}>
<div>
<Header />
<RouteList />
<Footer />
</div>
</Router>
);
}
}
export default App;
--EDIT--
Added my webpack.config.js
const commonConfig = {
resolve: {
modules: [path.resolve('./src'), 'node_modules'],
extensions: ['.js', '.csv', '.json', '.scss', '.css', '.html']
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
enforce: 'pre',
use: [{ loader: 'eslint-loader', options: { configFile: '.eslintrc' } }]
},
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
test: /\.html$/,
use: [{ loader: 'htmlhint-loader', options: { configFile: '.htmlhintrc' } }],
exclude: /node_modules/,
enforce: 'pre'
},
{
test: /\.(png|jpg|jpeg|svg|gif|svg|woff|woff2|ttf|eot)(\? v=\d+\.\d+\.\d+)?$/,
use: 'file-loader'
},
{
use: [{
loader: 'html-loader'
}],
test: /\.html$/
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv)
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module) {
if (module.resource && (/^.*\.
(css|less|scss)$/).test(module.resource)) {
return false;
}
return module.context && module.context.indexOf('node_modules') !== -1;
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
new CopyWebpackPlugin([{
from: __dirname + '/src/images',
to: ''
}]),
new HtmlWebpackPlugin({
template: 'src/index.html',
chunksSortMode: 'dependency'
}),
new webpack.optimize.ModuleConcatenationPlugin()
]
};
const devConfig = {
entry: {
main: ['whatwg-fetch', 'core-js/es6', 'react-hot-loader/patch', 'index.js',
'webpack-hot-middleware/client?reload=true']
},
target: 'web',
devtool: 'inline-source-map',
output: {
path: path.join(__dirname, '/dev_build'),
filename: '[name].bundle.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.scss/,
include: path.resolve(__dirname, 'src/styles'),
use: ['style-loader', 'css-loader', {loader: 'sass-loader', options:
{sourceMap: true}}]
},
{
test: /\.css$/,
exclude: [/node_modules/],
use: ['style-loader', 'css-loader?modules']
},
{
test: /\.css$/,
include: [/node_modules/],
use: ['style-loader', 'css-loader']
}
]
},
devServer: {
contentBase: 'src',
compress: true,
hot: true,
port: 3000,
host: '0.0.0.0',
disableHostCheck: true,
historyApiFallback: {
disableDotRule: true,
index: 'build/index.html'
},
stats: 'minimal',
overlay: true,
proxy: {
'/api/**': {
target: {
port: 8080
},
secure: false
},
'/actuator/**': {
target: {
port: 8080
},
secure: false
},
}
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin()
]
};
Please help cause I am not sure what I am doing wrong and i am splitting my brains over this. Thanks.
You can add a Redirect from / to /extension if you want that to be the landing page.
const RouteList = () => (
<Switch>
<Redirect from='/' to='/extension/'/>
<Route path="/extension/" exact component={HomePage} />
<Route path="/extension/something" exact component={SomethingPage} />
<Route component={Error} />
</Switch>
);
Your app currently only works when visited on / because your server will only serve index.html for the index route. You can use historyApiFallback if you want the index.html file to be served instead of any 404 responses.
webpack.config.js
module.exports = {
//...
devServer: {
historyApiFallback: true
}
};

Webpack and React BrowserRouter

im working on a project that was made in react with hashrouter, i want to change to browserouter but the project already has a webpack config and im kind of new to it, i know i should make webpack to take all calls to index (since im getting Cannot get on all routes) but i cant find any info on this kind of setup:
This is the current webpack config
const path = require('path');
const webpack = require('webpack');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
module.exports = {
devtool: 'cheap-module-source-map',
entry: {
app: [
'webpack-hot-middleware/client',
'react-hot-loader/patch',
'./src/app'
]
},
resolve: {
modules: ['node_modules'],
extensions: ['.js', '.jsx', '.scss'],
alias: {
'react-native': 'react-native-web'
}
},
output: {
path: path.join(__dirname, 'public/assets'),
publicPath: '/assets/',
filename: '[name].bundle.js'
},
module: {
rules: [{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [{
loader: 'react-hot-loader/webpack'
}, {
loader: 'babel-loader', options: {cacheDirectory: '.babel-cache'}
}]
}, {
// Most react-native libraries include uncompiled ES6 JS.
test: /\.js$/,
include: [
/node_modules\/react-native-/,
/node_modules\/react-router-native/,
/node_modules\/#indec/
],
loader: 'babel-loader',
query: {
presets: ['react-app'],
cacheDirectory: '.babel-cache'
}
}, {
test: /\.scss$/,
loader: [
'css-hot-loader'
].concat(
ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
)
}, {
test: /\.css$/,
use: ['style-loader', 'css-loader']
}, {
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.json$/,
/\.s?css$/,
/\.(jpg|png)/
],
loader: 'url-loader',
options: {name: '[name].[ext]', limit: 10000}
}, {
test: /\.(jpg|png)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
options: {name: '[name].[ext]'}
}]
},
plugins: [
new webpack.DefinePlugin({
VERSION: JSON.stringify(require('./package.json').version),
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
ENDPOINT: JSON.stringify(require('./config.json').endpoint)
}),
new webpack.optimize.CommonsChunkPlugin('vendor'),
new webpack.HotModuleReplacementPlugin(),
new CaseSensitivePathsPlugin(),
new FriendlyErrorsWebpackPlugin(),
new ExtractTextPlugin('[name].bundle.css')
],
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
app gets initiated on this index.js file
const path = require('path');
const app = require('connect')();
const config = require('./config.json');
const winston = require('winston');
const PORT = process.env.PORT || config.server.port;
process.env.NODE_ENV = config.mode;
app.use(require('morgan')(config.server.morgan));
app.use(require('compression')());
app.use(require('serve-static')(path.join(__dirname, config.server.static)));
if (config.mode === 'development') {
const config = require('./webpack.config');
const compiler = require('webpack')(config);
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: config.output.publicPath,
}));
app.use(require('webpack-hot-middleware')(compiler));
}
require('http').createServer(app).listen(
PORT,
() => winston.info('Server started at port %s', config.server.port)
);
and my app js
import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import Aux from 'react-aux';
import Home from '../Home';
import Admin from '../Admin';
import SignIn from '../SignIn';
import Header from './Header';
import Footer from './Footer';
const App = () => (
<BrowserRouter>
<Aux>
<Header/>
<main>
<Switch>
<Route path="/" component={Home}/>
<Route path="/admin" component={Admin}/>
<Route path="/signIn" component={SignIn}/>
</Switch>
</main>
</Aux>
</BrowserRouter>
);
export default App;
I end up finding a easy solution, just created a express app and handled all 404 to index, didn't find how to do it with connect.
const path = require('path');
const express = require('express');
const app = express();
const config = require('./config.json');
const winston = require('winston');
const PORT = process.env.PORT || config.server.port;
process.env.NODE_ENV = config.mode;
app.use(require('morgan')(config.server.morgan));
app.use(require('compression')());
app.use(require('serve-static')(path.join(__dirname, config.server.static)));
if (config.mode === 'development') {
const config = require('./webpack.config');
const compiler = require('webpack')(config);
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: config.output.publicPath,
}));
app.use(require('webpack-hot-middleware')(compiler));
}
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, './public/index.html'), function(err) {
if (err) {
res.status(500).send(err);
}
});
});
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
require('http').createServer(app).listen(
PORT,
() => winston.info('Server started at port %s', config.server.port)
);
You can use historyApiFallback: true in your config to do this.
Docs on that are located here

Can't get webpack require.ensure chunking method to work with react-router and generate separate bundle files

I would like to use webpack chunking method to generate separate bundles for separate routes in my route config.
One way to achieve it is to use require.ensure to define split points for chunks and asynchronously load modules on browser demand.
Here is what I ve got:
webpack.config.js (merged with dev/prod webpack configs depending on executed npm script):
var autoprefixer = require('autoprefixer');
var html = require('html-webpack-plugin');
var path = require('path');
var webpack = require('webpack');
var node_modules_dir = path.resolve('./node_modules')
var HappyPack = require('happypack');
module.exports = {
context: path.resolve('./src'),
entry: {
app: ['./scripts/index.js', './styles/index.scss'],
vendor: ['react', 'react-dom', 'react-redux', 'redux','immutable'],
},
module: {
loaders: [
{
test: /\.(jpg|png|gif|json)$/,
loader: 'file',
query: {
name: 'assets/[hash].[ext]',
},
},
{
test: /\.svg$/,
loader: 'happypack/loader?id=svg'
},
],
},
output: {
filename: '[name].js',
path: path.resolve('./build'),
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
// new webpack.optimize.LimitChunkCountPlugin({maxChunks: 5}),
// new webpack.optimize.MinChunkSizePlugin({minChunkSize: 10000}),
new html({
minify: {
collapseWhitespace: true,
},
template: './index.html',
title: process.env.npm_package_config_title,
}),
new webpack.optimize.CommonsChunkPlugin('vendor','vendor.bundle.js'),
new HappyPack({
id: 'svg',
threads: 5,
loaders: [
'svg-inline'
]
})
],
postcss: function() {
return [
autoprefixer,
];
},
resolve: {
alias: {
assets: path.resolve('./src/assets'),
lib: path.resolve('./src/lib'),
modules: path.resolve('./src/scripts/modules'),
scripts: path.resolve('./src/scripts'),
styles: path.resolve('./src/styles'),
toolbox: path.resolve('./node_modules/react-toolbox'),
vendors: path.resolve('./src/vendors'),
'react-redux': node_modules_dir + '/react-redux/dist/react-redux.min.js',
'redux': node_modules_dir + '/redux/dist/redux.min.js',
'immutable': node_modules_dir +'/immutable/dist/immutable.min.js'
},
extensions: [
'',
'.js',
'.jsx',
'.css',
'.scss',
],
},
toolbox: {
theme: path.resolve('./toolbox/index.scss'),
},
};
webpack.config.dev.js (dev webpack configuration [merged with above]):
var merge = require('webpack-merge');
var webpack = require('webpack');
var path = require('path');
var config = require('./config');
var HappyPack = require('happypack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = merge(config, {
// devtool: 'eval',
devServer: {
contentBase: 'build',
historyApiFallback: true,
hot: true,
host: '0.0.0.0',
inline: true,
port: parseInt(process.env.npm_package_config_port),
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'happypack/loader?id=jsx'
},
{
test: /\.s?css$/,
loader: 'happypack/loader?id=css'
},
],
},
output: {
chunkFilename: "[name].js",
publicPath: 'http://localhost:' + process.env.npm_package_config_port + process.env.npm_package_config_public_path,
pathInfo: true,
},
plugins: [
new webpack.PrefetchPlugin('react'),
new webpack.PrefetchPlugin('react-toolbox'),
new webpack.PrefetchPlugin('react-redux'),
new webpack.PrefetchPlugin('redux'),
new webpack.PrefetchPlugin('immutable'),
new webpack.PrefetchPlugin('./scripts/routes.jsx'),
new webpack.PrefetchPlugin('./scripts/components/smart/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/login/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/companies_list/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/shortlists/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/testing_shortlist/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/components/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/horizontal_chart/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/smarts/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/view_content/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/views/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/refactorized_tools/components/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/refactorized_tools/composed/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/refactorized_tools/view_content/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/refactorized_tools/views/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/tools/cities_list_with_filters/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/tools/city_path_start/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/tools/company_path_start/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/tools/compare_cities_datapoints/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/tools/compare_companies_datapoints/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/tools/compare_result/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/tools/scan_your_brand/index.jsx'),
new webpack.PrefetchPlugin('./scripts/components/views/tools.old/tools/subcomponents/index.jsx'),
new webpack.PrefetchPlugin('./lib/ui/multi_select/RTAutocomplete/index.js'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/view_content/charts/style/charts.scss'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/view_content/filters_box/style/city.scss'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/view_content/filters_box/style/company.scss'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/view_content/map_with_bottom_stats/style.scss'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/view_content/city_boxes/style/city_boxes.scss'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/view_content/company_boxes/style/company_boxes.scss'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/view_content/filters_box_with_header_box/style/city.scss'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/view_content/filters_box_with_header_box/style/company.scss'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/view_content/selected_entities/style/selected_entities.scss'),
new webpack.PrefetchPlugin('./scripts/components/views/tools/view_content/human_resources_table_box/style/_human_resources_table_box.scss'),
// new webpack.PrefetchPlugin(''),
new ExtractTextPlugin("[hash].css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
'process.env.LANDING_ONLY': JSON.stringify(false),
}),
new webpack.HotModuleReplacementPlugin(),
new HappyPack({
id: 'jsx',
threads: 5,
loaders: ['babel?presets[]=react-hmre']
}),
new HappyPack({
id: 'css',
threads: 5,
loaders: [
'style',
'css?sourceMap,modules,localIdentName=[local]__[hash:base64:5]',
'postcss',
'resolve-url',
'sass?sourceMap',
'toolbox'
]
})
],
});
routes.jsx:
[some module imports here]
export default (
<Route component={ PermisionProvider } >
<Route component={ AppProvider } >
<Route component={ SnackbarProvider } >
<Redirect from={ paths.root } to={ localStorage.get('user') ? paths.login : paths.landingPageCities } />
{ /* Landing */ }
<Route onEnter={ _hasPermission.bind(null, 'landingPage') }>
<Route component={ LandingLayout }>
<Route
path={ paths.landingPageCities }
getComponent={(location, callback) => {
require.ensure(['modules/landing_page/smarts/SmartLandingCities'], function (require) {
callback(null, require('modules/landing_page/smarts/SmartLandingCities').default);
}, 'SmartLandingCities');
}}
/>
<Route
path={ paths.landingPageCompanies }
getComponent={(location, callback) => {
require.ensure(['modules/landing_page/smarts/SmartLandingCompanies'], function (require) {
callback(null, require('modules/landing_page/smarts/SmartLandingCompanies').default);
}, 'SmartLandingCompanies');
}}
/>
<Route
path={ paths.aboutUsPage }
getComponent={(location, callback) => {
require.ensure(['modules/landing_page/views/AboutUsPage'], function (require) {
callback(null, require('modules/landing_page/views/AboutUsPage').default);
}, 'AboutUsPage');
}}
/>
</Route>
</Route>
{ /* Login */ }
<Route onEnter={ _hasPermission.bind(null, 'login') }>
I read tones of blog posts and tutorials and it all seems to be in place here. Yet, webpack is not generating separate bundles for neither of the routes in which I use require.ensure:
SmartLandingCities
SmartLandingCompanies
AboutUsPage
Am super desperate already, as the app bundle is 2mb in size and I already used all available size shrinking methods out there.
Thanks for any help!
Since there already been three requests for access to repo that contains working solution, here it is:)
Have a great coding!
https://bitbucket.org/azrahel/crit_calendar/

Resources