javascript - How to generate unique file name using webpack? - Stack Overflow

admin2025-04-20  0

I have webpack config configuration , I would like to generate a unique file name eg name123fr every time I run nmp run build, here is part of my code

return [{
        entry: './src/main.js',
        output: {
            filename: 'widget.js',
            path: path.resolve(bundleOutputDir),
        }
}]

This generates me the following file: http://localhost:8080/widget.js

But I want something like this http://localhost:8080/widget23we23.js

the name should be unique each time I run `npm run build'

is this possible using webpack?

I have webpack config configuration , I would like to generate a unique file name eg name123fr every time I run nmp run build, here is part of my code

return [{
        entry: './src/main.js',
        output: {
            filename: 'widget.js',
            path: path.resolve(bundleOutputDir),
        }
}]

This generates me the following file: http://localhost:8080/widget.js

But I want something like this http://localhost:8080/widget23we23.js

the name should be unique each time I run `npm run build'

is this possible using webpack?

Share Improve this question asked Feb 2, 2020 at 21:29 The Dead ManThe Dead Man 5,57633 gold badges125 silver badges226 bronze badges 2
  • Will this do what you want? From the docs: "The [contenthash] substitution will add a unique hash based on the content of an asset. When the asset's content changes, [contenthash] will change as well." – David784 Commented Feb 2, 2020 at 21:33
  • let me check out , thx – The Dead Man Commented Feb 2, 2020 at 21:35
Add a ment  | 

1 Answer 1

Reset to default 6

The webpack documentation on caching remends using the [contenthash] substitution:

The [contenthash] substitution will add a unique hash based on the content of an asset. When the asset's content changes, [contenthash] will change as well.

here's an example of what that would look like in your code snippet from above:

const HtmlWebpackPlugin = require('html-webpack-plugin');
// ...
return [{
  entry: './src/main.js',
  plugins: [
    new HtmlWebpackPlugin({ title: 'Caching' }),
  ],
  output: {
    filename: 'widget.[contenthash].js',
    path: path.resolve(bundleOutputDir),
  }
}]

The output should then be something like this:

widget.7e2c49a622975ebd9b7e.js

This won't do exactly what you ask, because the name won't change with every single reload. But it will cause the file name to change when the code changes, and I suspect this is your desired oute.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745085343a284105.html

最新回复(0)