0

I'm trying to build a basic react lazy app using the webpack. it creates the chunk successfully but when the app is running it looks for the chunk in the wrong directory, therefore, app crashes. My build directory is the dist, and I put my js files in dist/js directory but it looks in the root for the chunk(root directory of live-server). This is the implementation:

Home component:

import React,{lazy, Suspense} from 'react'
import { render } from 'react-dom'
const Info = lazy(() => import('./Info'))

class Home extends React.Component{
    state = {
        show: false,
    }

    toggleShow = () => this.setState(prevState => ({ show: !prevState.show }));

    render(){
        console.log
        return (
            <div>
                <h1>React lazy - today</h1>
                {this.state.show && (
                    <Suspense fallback={<div>something went wrong</div>}>
                        <Info/>
                    </Suspense>
                )}
                <button onClick={this.toggleShow}>toggle show</button>
            </div>
        )
    };
}

render(<Home/>, document.querySelector('#app'));

Info component:

import React from 'react'

export default (props) => (
    <div>This is secure information</div>
);

webpack:

const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    entry: {
        app: './src/lazy/Home.js'
    },
    output:{
        publicPath: '/',
        path: path.join(__dirname, 'dist/js'),
        filename: '[name].bundle.js'
    },
    module:{
        rules:[
            {
                loader: 'babel-loader',
                test:/\.js$/,
                exclude: /node_modules/
            }
        ]
    },
    plugins:[new CleanWebpackPlugin()],
    mode:'development'
};

Problem solved: I was using live-server to run the app. I tried webpack-dev-server so then it got solved.

Jora
  • 191
  • 2
  • 13
  • I had the best experience using react lazy when the folders were in the same folder as the one using the import, or if they were inside a child folder of that folder, anywhere else i got chunk error. – Ali Ahmadi Dec 24 '19 at 10:20
  • @AliAhmadi it worked that way but it gets mess if chunks start to grow – Jora Dec 24 '19 at 11:46
  • 1
    @Jora can you add the solution as an answer to the question? So that fellow StackOverflowians don't perceive this as an un-answered / unresolved question. – Pat Needham Dec 24 '19 at 23:50
  • 1
    @PatNeedham Yeah sure. Thanks for advice – Jora Dec 24 '19 at 23:51

1 Answers1

1

Problem Solved: I was using live-server to run the app. I tried webpack-dev-server so then it got solved.

Jora
  • 191
  • 2
  • 13