我正在尝试使用 webpack 构建一个基本的反应惰性应用程序。它成功创建了块,但是当应用程序运行时,它在错误的目录中查找块,因此,应用程序崩溃。我的构建目录是dist
,我将我的 js 文件放在 dist/js 目录中,但它在根目录中查找块(实时服务器的根目录)。这是实现:
家庭组件:
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'));
信息组件:
import React from 'react'
export default (props) => (
<div>This is secure information</div>
);
网络包:
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'
};
问题 已解决:我使用 live-server 运行应用程序。我尝试了 webpack-dev-server 所以它得到了解决。