How can i split code with webpack for a html project?

32 Views Asked by At

I am trying to setup my html project with webpack. I am also using tailwind. I want to split my code so that i don't have to copy and paste same code.

Example:

Document


<!-- header.html goes here  -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- header.html goes here  -->

    <!-- footer.html goes here  -->
  </body>
</html>

I've used html-webpack-simple-include-plugin and it works but when i try to make some changes in the code that I've split, It doesn't work. I've to reload the server to see the changes.

webpack.config.js file

const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const fs = require('fs');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const HtmlWebpackSimpleIncludePlugin = require("html-webpack-simple-include-plugin");

module.exports = {
  entry: {
    main: "./src/index.js",
  },
  mode: "development",
  devServer: {
    watchFiles: ["src/**/*"],
    hot: true,
    caches:false,
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        include: path.resolve(__dirname, "src"),
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
        ],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      }
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'styles.css',
    }),
    new CopyPlugin({
      patterns: [
        { from: "src/assets", to: "assets" }
      ],
    }),
    new HtmlWebpackPlugin({
      template: "src/index.html",
      hash:true,
    }),
    new HtmlWebpackPlugin({
      filename: "about.html", 
      template: "src/about.html", 
      hash:true,
    }),
    new HtmlWebpackSimpleIncludePlugin([
      {
        tag: '<include-footer />',
        content: fs.readFileSync(path.resolve(__dirname, "src/partials/footer.html")),
        hash:true,
      },
      {
        tag: '<include-header />',
        content: fs.readFileSync(path.resolve(__dirname, "src/partials/header.html")),
        hash:true,
        caches:false,
      }
    ])
  ],
  output: {
    filename: "index.js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
  },
};

Is there any other way to accomplish this. Please help

0

There are 0 best solutions below