Home > Back-end >  vite: Adding static assets(with cache busting) to the build
vite: Adding static assets(with cache busting) to the build

Time:08-30

I have large static files which should be busted with a hash for HTTP-caching. If I put them into the public directory, vite only copies them without appending a hash to the filenames. If I put them into the assets directory, vite ignores them, because they are not referenced directly from code, but loaded via XHR requests. The directory structure is pretty standard:

/
├─ src/
│  ├─ assets/
│  │  ├─ locales/
│  │  │  ├─ en.json
│  │  │  ├─ de.json
│  │  │  ├─ ru.json
│  ├─ main.js
├─ public/
├─ dist/
├─ index.html

How do I tell vite to copy those files with hash added to filenames and how do I get the resulting filenames to use them in XHR requests?

CodePudding user response:

One solution is to use the url suffix to import the .json:

// BEFORE:
// fetch('@/assets/locales/en.json').then(res => res.json()).then(json => /*...*/)

// AFTER:                                              
  • Related