0

我正在尝试将HMR添加到我现有的项目中。那么让我们从当前如何管理这些东西开始吧。为webpack中的多个HtmlWebpackPlugin输出添加HMR

我有多个HTML文件,需要在不同的路线上提供服务。因此,对于​​页面,我需要提供about.html,以及整个反应应用程序的JavaScript。所以这就是我现在的代码的样子:

webpack.config.js中,我使用HtmlWebpackPlugin为它们的chunkhash添加标题和js文件。

new HtmlWebpackPlugin({ 
    title: `Welcome to my app`, 
    template: './build/index.html', 
}), 
new HtmlWebpackPlugin({ 
    title: `Welcome to my app`, 
    filename: 'about.html', 
    template: './build/about.html', 
}), 
new HtmlWebpackPlugin({ 
    title: `Welcome to my app`, 
    filename: 'base.html', 
    template: './build/base.html', 
}), 
new webpack.HotModuleReplacementPlugin(), 

这就是webpack配置中的“输出”的样子。我将publicPath设置为'/'。

output: { 
    path: path.resolve(__dirname, '..', 'build'), 
    publicPath: '/', 
    filename: 'js/[name]-[hash].js', 
    }, 

这是我server.js文件看起来像,在那里我使用的WebPack-DEV-中间件和的WebPack热中间件。

const compiler = require('webpack')(webpackConfig); 
app.use(require('webpack-dev-middleware')(compiler, { 
    publicPath: webpackConfig.output.publicPath, 
    colors: true, 
})); 

app.use(require('webpack-hot-middleware')(compiler, { 
    quiet: true, 
    noInfo: true, 
    log: console.log, 
    path: '/__webpack_hmr', 
})); 

这是如何我服务的HTML文件:

app.get('/', (req, res) => res.sendFile(path.join(__dirname, '/../build/index.html'))); 
app.get('/about', (req, res) => res.sendFile(path.join(__dirname, '/../build/about.html'))); 
app.get('/status', (req, res) => res.send('Status OK')); 
app.get('*', (req, res) => res.sendFile(path.join(__dirname, '/../build/base.html'))); 

现在,当我打开路线的/,一切都与HMR一起的伟大工程。但是,无论何时我打开​​或/anything,都会加载about.html或base.html,但没有添加应用程序脚本。

为什么它为索引路由而不是其他路由工作?感谢您的帮助:)

+0

你能告诉你的WebPack入门配置试试? –

回答