Using webpack's hash in JavaScript for cache busting

Can someone guide me on adding a hash to my js file name for cache-busting purposes? I've researched online but still uncertain about where to include the [hash] element. Any help would be appreciated.

Provided below is a snippet from my webpack.config file:

const devCerts = require("office-addin-dev-certs");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const fs = require("fs");
const webpack = require("webpack");

module.exports = async (env, options) => {
  const dev = options.mode === "development";
  const config = {
    devtool: "source-map",
    entry: {
      polyfill: "@babel/polyfill",
      jquery: "jquery/src/jquery",
      taskpane: "./src/taskpane.ts",
      sentry: "@sentry/browser"
    },
    resolve: {
      extensions: [".ts", ".tsx", ".html", ".js"]
    },
    module: {
      rules: [
        {
          test: /\.ts$/,
          exclude: /node_modules/,
          use: "babel-loader"
        },
        {
          test: /\.tsx?$/,
          exclude: /node_modules/,
          use: "ts-loader"
        },
        {
          test: /\.html$/,
          exclude: /node_modules/,
          use: "html-loader"
        },
        {
          test: /\.(png|jpg|jpeg|gif)$/,
          use: "file-loader"
        }
      ]
    },
    plugins: [
      new CleanWebpackPlugin(),
      new HtmlWebpackPlugin({
        filename: "taskpane.html",
        template: "./src/taskpane.html",
        chunks: ["polyfill", "jquery", "taskpane", "sentry"]
      }),
      new CopyWebpackPlugin([
        {
          to: "taskpane.css",
          from: "./src/taskpane.css"
        }
      ]),
      new CopyWebpackPlugin([
        {
          to: "assets",
          from: "./assets"
        }
      ]),
      new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery"
      })
    ],
    devServer: {
      headers: {
        "Access-Control-Allow-Origin": "*"
      },      
      https: (options.https !== undefined) ? options.https : await devCerts.getHttpsServerOptions(),
      port: process.env.npm_package_config_dev_server_port || 3000
    }
  };

  return config;
};

Answer №1

Insert this code snippet after entry: { ... },

    output: {
      filename: '[name].[hash].js',  // consider using [contenthash] for better caching
      path: path.resolve(__dirname, 'dist'),
    },
    optimization: {
      runtimeChunk: 'single',
    },

If you want Webpack to generate files in the ./dist subdirectory.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Javascript - The art of accessing an anonymous array

I'm trying to extract data from an API, but I've run into a snag. There's a list without a name attached to it, making it impossible for me to access the values inside. Here's a simplified example of what I mean: (Here is the JSON stru ...

Encountering a server issue while incorporating ejs in expressjs

I am a beginner with nodejs and I am experimenting with using ejs to template my website. However, every time I try to set the view engine, I encounter the error 500 - Internal Server Error. Here is my app.js: var express = require('express'); v ...

Tips for distinguishing between 1 and 1.00 as equal, and 1.01 as not equal in Angular

How should the number 1 be treated when the decimals are zero, for example 1.000? In this case, an alert popup should appear indicating that the numbers are the same. The maximum length of the textbox should be 7 characters. For instance, 1 and 1.00000001 ...

Why is my Angular Reactive form not retrieving the value from a hidden field?

I've encountered a problem where the hidden field in my form is not capturing the product id unless I manually type or change its value. It consistently shows as "none" when submitting the form. TS https://i.stack.imgur.com/W9aIm.png HTML https://i. ...

What are the common reasons for jQuery Image Slider malfunctioning?

After following a tutorial on Youtube (https://www.youtube.com/watch?v=KkzVFB3Ba_o) about creating a JQuery image gallery, I realized that my implementation is not working at all. Despite carefully reviewing my code and fixing any errors I could find, the ...

Sort out the information in the table

Seeking assistance on how to filter a table based on certain conditions. Refer to the sample image provided in the link below: https://i.sstatic.net/Egvj6.png Here is the code I have attempted: this.reportData.filter(it => { if ( ...

Unleashing the power of TypeScript in combination with svelte and d3

Currently, I am facing an issue with TypeScript regarding data types. Specifically, I am working on a Svelte component for the x-axis of a d3 visualization. In this component, I receive the xScale as a property from the parent component like this: <XAix ...

Conditions for JQuery Ajax handlingIs there anything specific you would

I am looking to implement a try-catch scenario in Laravel where, if successful, a certain message will appear and if it fails, a different message will be displayed. However, when executed successfully, it seems to display the second message instead. $.a ...

Changing images dynamically in tinymce using JavaScript

When using the tinymce editor, I attempt to modify my images. I currently have an image within it and I am trying to dynamically change the path of this image with: tinymce.activeEditor.selection.getNode().src = '/my/path/' Surprisingly, this m ...

encountering an issue with the react hook useHistory leading to an error

I recently encountered an issue while implementing useHistory() in my code. Previously, I had used it without any errors, but now I'm getting the following error in this component: Line 6:18: React Hook "useHistory" is called in function "showPost" ...

Having multiple upload forms on a single page with PHP, AJAX, and jQuery is not functioning as expected

I'm on the hunt for a jQuery-AJAX image uploader that supports multiple instances of the form on a single page. Do you have any recommendations? Here's my scenario: I have a front-end page where users can update their profiles. Upon loading the ...

Placing content retrieved from a MySQL database within a form displayed in a ColorBox

Having difficulty inserting text from a MySQL database into a form (textfield) inside a ColorBox. The current script is as follows: <a href="#" class="bttn sgreen quote1">Quote</a> var postQuote[<?php echo 4id; ?>]=<?php echo $f ...

Does Angular perform tree shaking on a service that is provided at the root level, as long as it is not explicitly injected into a component instance?

Suppose we implement a service similar to this as part of a library: @Injectable({ providedIn: 'root' }) export class ChartJSProvider { constructor() { Chart.register(...registerables); } } and our application makes use of the aforem ...

Encountering an issue with Google distance matrix where property 'text' is undefined

Below is a snippet of code that calculates the distance between two user-provided addresses. This code currently runs when the user submits a form in this manner: $("#distance_form").submit(function (e) { e.preventDefault(); calculateDistance(); }); ...

Searching for two distinct nested key values in Ramda

I am new to Ramda and wondering if it is possible to retrieve two different key values at the same level of an object. Below is the code I have added: In this scenario, the object 'list' contains keywords 'users' and 'employee&ap ...

Node.js application experiencing bug with End of Line (EOL) not displaying correctly

I've encountered an issue with my node.js application that involves writing the following code: word_meaning = 'line 1' + os.EOL +'line 2'; When attempting to render this in an HTML file using the following code: <p> <% ...

JSON data converted into an adjacency list

I am attempting to programmatically create a new object in the form of an adjacency list using the provided sampleData. This object will be used in jointJS to generate an organization chart: sampleData = [ {"id":"1224286", "label":"someLabel1", "image ...

Adding content to the parent element immediately after it is generated using jQuery

Is there a way to trigger $(e).append() as soon as the element e is created without using setTimeout()? I find that method inefficient. Are there any DOM events that can detect changes in a subtree of a DOM element? Usually, I would just add the code to t ...

Special VueJs rendering for JSON data retrieval from API

Here is the data I received from an API: { "data": { "City": { "zip": "75000", "appointment": { "2020-10-12": { "08:00:00": 3, "09:15:0 ...

Learn how to create a validation function for phone numbers in a React application that keeps the button disabled until a valid phone number

import React,{useState} from "react"; export default function ValidatePhone() { const [phoneNumber, setPhoneNumber] = useState(""); const [disableButton, setDisableButton] = useState(true); function handleChange(e) { setPho ...