In a project built by Vite, index.html is usually the entry point of the project. While we can put the copyright notice in the JavaScript bundle, it is often desirable to add it directly to the HTML file for various reasons. For example, maybe the copyright notice is entangled with the privacy policy or terms of service links, which we usually want to make visible even when the user turns off JavaScript.

A straightforward solution is to add a copyright notice with a fixed year to the footer like:

<footer>
  Copyright &copy; 2024 My Name
</footer>

However, it can be quite annoying to bump the year in every project, even though it’s only once per year.

In this post, we present a simple and clean solution to address this problem using the HTML transformation hook of Vite. This solution does not use in-page JavaScript so that users can see them even without JavaScript enabled. We have also created a package @8hobbies/vite-plugin-year that uses the solution from this post for your convenience.

Using Vite’s HTML Transformation Hook

The core idea is to use a token such as __YEAR__ in the HTML file and let Vite replace it with the current year.

1. Define the HTML Transformation Plugin Object

In vite.config.ts/vite.config.js, define the HTML transformation plugin object that replaces __YEAR__ with the current year:

function yearPlugin() {
  return {
    name: "year",
    transformIndexHtml(html: string): string {
      return html.replace("__YEAR__", new Date().getFullYear().toString());
    },
  } as const;
}

2. Enable the Plugin

In vite.config.ts/vite.config.js, enable the plugin by adding yearPlugin to the plugin list:

export default defineConfig({
  // ...
  plugins: [
    // ...
    yearPlugin(),
  ],
});

In index.html, add the following:

<footer><p>Copyright &copy; __YEAR__ My Name</p></footer>

Now build the site with Vite. We should now see a copyright notice that always has the current year upon build.

Conclusion

We discussed a simple and clean solution to add a copyright notice with the current year to the HTML file in a Vite project. This solution does not use in-page JavaScript so that users can see them even without JavaScript enabled. For your convenience, we have also packed this solution as a package, @8hobbies/vite-plugin-year.