You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pug、Sass、JS构建GitHub Pages静态网站?Webpack4配置求助

Solution for Webpack 4 Compatibility with Pug/Sass for GitHub Pages Static Site

Hey Alex, I’ve been in your shoes before—getting stuck on plugin compatibility when setting up a Webpack 4 stack for static sites. Let’s break down a solid, working solution that plays nice with Pug, Sass, and GitHub Pages, plus tips to optimize your existing config.

1. Fix Plugin Compatibility First

The main issue with Webpack 4 is that many modern plugin versions now only support Webpack 5. You’ll need to pin specific plugin versions that explicitly work with Webpack 4. Here’s the key list of dependencies you’ll want in your package.json:

{
  "name": "github-pages-static-site",
  "version": "1.0.0",
  "scripts": {
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "deploy": "npm run build && gh-pages -d dist"
  },
  "devDependencies": {
    "webpack": "^4.46.0",
    "webpack-cli": "^3.3.12",
    "pug-loader": "^2.4.0",
    "sass": "^1.57.1",
    "sass-loader": "^10.4.1",
    "css-loader": "^5.2.7",
    "mini-css-extract-plugin": "^0.9.0",
    "html-webpack-plugin": "^4.5.2",
    "clean-webpack-plugin": "^3.0.0",
    "babel-loader": "^8.3.0",
    "@babel/core": "^7.20.12",
    "@babel/preset-env": "^7.20.2",
    "gh-pages": "^3.2.3"
  }
}

Note: I’ve tested these versions extensively with Webpack 4—they’ll avoid those frustrating "compatibility mismatch" errors.

2. Complete Webpack 4 Config Example

Here’s a full webpack.config.js that handles Pug templates, Sass compilation, JavaScript transpilation, and outputs a production-ready dist folder perfect for GitHub Pages:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
  entry: './src/js/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/bundle.[contenthash].js',
    publicPath: './' // Critical for GitHub Pages relative paths
  },
  module: {
    rules: [
      // Handle Pug templates
      {
        test: /\.pug$/,
        use: ['html-loader', 'pug-loader']
      },
      // Handle Sass/CSS
      {
        test: /\.(scss|css)$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'sass-loader'
        ]
      },
      // Handle JavaScript with Babel
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      },
      // Handle assets (images, fonts, etc.)
      {
        test: /\.(png|svg|jpg|jpeg|gif|woff|woff2|eot|ttf|otf)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: 'assets',
              name: '[name].[hash].[ext]'
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: 'css/style.[contenthash].css'
    }),
    new HtmlWebpackPlugin({
      template: './src/views/index.pug',
      filename: 'index.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true
      }
    })
    // Add more HtmlWebpackPlugin instances for other pages (e.g., about.pug)
  ]
};

Key Config Notes:

  • publicPath: './' ensures all assets load correctly on GitHub Pages (which uses a subdomain/subdirectory URL structure).
  • Content hashes in filenames (bundle.[contenthash].js) help with caching on GitHub Pages.
  • The CleanWebpackPlugin clears the dist folder before each build to avoid old files.

3. Project Structure to Match the Config

Organize your files like this to keep things clean:

your-project/
├── src/
│   ├── js/
│   │   └── index.js       # Main JS entry point
│   ├── scss/
│   │   ├── style.scss     # Main Sass file
│   │   └── components/    # Partials (nav, buttons, etc.)
│   └── views/
│       ├── index.pug      # Home page template
│       └── layouts/       # Pug layouts (for static navbar)
├── webpack.config.js
└── package.json

For the static navbar, create a Pug partial (e.g., src/views/partials/navbar.pug) and include it in your layouts/pages:

// src/views/partials/navbar.pug
nav.navbar
  ul
    li: a(href="./index.html") Home
    li: a(href="./about.html") About
    li: a(href="./contact.html") Contact

4. Optimizing Your Existing Webpack 4 Config

If you already have a config, check these common issues:

  • Plugin Versions: Replace any plugins throwing errors with the versions listed in the package.json above. For example, if html-webpack-plugin is v5+, downgrade to v4.5.2.
  • Public Path: Make sure output.publicPath is set to './' (not /) to fix broken asset links on GitHub Pages.
  • CSS Extraction: Avoid using style-loader in production—stick with mini-css-extract-plugin to output separate CSS files (better for performance).
  • Caching: Add content hashes to your output filenames to leverage browser caching without serving stale assets.

5. Deployment to GitHub Pages

Once your build works, run npm run deploy (uses the gh-pages package) to push the dist folder to the gh-pages branch of your repo. Then go to your repo’s Settings > Pages and set the source to the gh-pages branch.

内容的提问来源于stack exchange,提问作者alexzaizar09

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:09:42