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入門配置試試? –

回答