使用Webpack v4+webpack-dev-server时Pug无法编译输出求助
Hey there! Let's troubleshoot why you're not seeing your compiled Pug content when running webpack-dev-server --mode development. I've looked over your config and spotted a few key issues that are likely causing this.
Key Problems in Your Current Config
webpack-dev-server stores files in memory (not disk)
YourdevServer.contentBasepoints to thedistdirectory, but in development mode, webpack-dev-server doesn't write compiled files to disk by default. Ifdistis empty, the server has no HTML file to serve.Missing
html-loaderfor Pug processingpug-loaderonly compiles Pug to raw HTML strings, but webpack needshtml-loaderto convert that string into a module thatHtmlWebpackPlugincan use to generate a proper HTML file.inject: falseblocks JS injection (not the root cause, but still problematic)
This setting preventsHtmlWebpackPluginfrom adding yourbundle.jsto the generated HTML, which will break your JS functionality even if the Pug content loads.
Corrected Webpack Config
Here's the adjusted config with fixes explained:
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/js/main.js', output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } }, { test: /\.pug$/, // Add html-loader to process the compiled Pug HTML string use: ['html-loader', 'pug-loader'] } ] }, devServer: { // Replace deprecated contentBase with static (webpack-dev-server v4 standard) static: { directory: path.join(__dirname, 'src') // Serve static assets from src if needed }, hot: true, open: true, progress: true }, plugins: [ new HtmlWebpackPlugin({ template: path.join(__dirname, 'src/templates/pages/index.pug'), // Inject bundle.js into the body (use true to inject into head instead) inject: 'body' }) ] };
Additional Steps to Ensure It Works
Install missing dependencies
Make sure you have all required packages installed:npm install --save-dev html-loader pug pug-loader html-webpack-plugin webpack-dev-serverRun the dev server again
Executewebpack-dev-server --mode developmentonce more. Now webpack-dev-server will serve the in-memory compiled HTML directly, so you should see your Pug content rendered in the browser.For production builds
If you need to generate physical files indist, run:webpack --mode production
内容的提问来源于stack exchange,提问作者zh-mskl9

