Ask Your Question
4

How can I convert classNames in HTML into hashed classNames in a VITE configuration with multiple pages?

asked 2022-01-14 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-12-27 07:00:00 +0000

bukephalos gravatar image

To convert classNames in HTML into hashed classNames in a VITE configuration with multiple pages, you can follow these steps:

  1. Install the posthtml-hash plugin:
npm i posthtml-hash --save-dev
  1. Create a posthtml.config.js file with the following contents:
const posthtmlHash = require("posthtml-hash");

module.exports = {
  plugins: [
    posthtmlHash({
      selector: "[class]",
      algorithm: "md5",
      hashLength: 8,
      manifest: "./dist/assets/hash-manifest.json",
    }),
  ],
};
  1. In your VITE configuration file, add the Html plugin and configure it to use the posthtml.config.js file:
// vite.config.js
import { defineConfig } from "vite";
import { createHtmlPlugin } from "vite-plugin-html";

export default defineConfig({
  plugins: [
    createHtmlPlugin({
      template: "public/index.html",
      filename: "index.html",
      minify: true,
      inject: true,
      hash: true,
      posthtml: {
        plugins: require("./posthtml.config"),
      },
    }),
    createHtmlPlugin({
      template: "public/page1.html",
      filename: "page1.html",
      minify: true,
      inject: true,
      hash: true,
      posthtml: {
        plugins: require("./posthtml.config"),
      },
    }),
    // more pages here
  ],
});
  1. Add the following code to your HTML templates where you want to use hashed classNames:
<!DOCTYPE html>
<html>
  <head>
    ...
  </head>
  <body>
    <div class="my-class">Hello World</div>
    ...
    <script src="/assets/main.js"></script>

    <% if (htmlWebpackPlugin.options.hash) { %>
      <script>window.__HASH_MANIFEST__ = <%= JSON.stringify(htmlWebpackPlugin.options.hash) %>;</script>
    <% } %>
  </body>
</html>

This will automatically hash the classNames in your HTML and update the references in your CSS and JavaScript files. The hashed classNames will be stored in a hash-manifest.json file in the ./dist/assets/ directory.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-14 11:00:00 +0000

Seen: 9 times

Last updated: Dec 27 '21