reactjsspringvue.jsvite

Vite - change static assets' directoy


I had build an app using create-react-app. And our server is set up as such that all files except index.html are in a folder named static.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <link rel="icon" type="image/svg+xml" href="./static/favicon.f99d69b1.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>App</title>
  
  <script type="module" crossorigin src="./static/index.81e5d079.js"></script>
  <link rel="modulepreload" href="./static/vendor.ba9c442b.js">
  <link rel="stylesheet" href="./static/index.f28d7853.css">
</head>
<body>
<div id="root"></div>

</body>
</html>


So JS file's path is ./static/js/main.836d2eb0.js.


And then I decided to go for Vite.

As you may know, Vite's default assets' directory is callled assets. I managed to change it to static by changing build.assetsDir to static in vite.config.js

  build: {
    assetsDir: "static",
    outDir: "./../backend/src/main/resources/static/app/",
  },

I changed the output's directory too.

After runing npm run build, all of the files are generated in the correct directory. However, CSS, JS, and other assets have wrong path, for ex, my JS file's path is /static/vendor.ba9c442b.js It lacks dot(.) before the first slush

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <link rel="icon" type="image/svg+xml" href="/static/favicon.f99d69b1.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Fiken Kundestøtte</title>
  
  <script type="module" crossorigin src="/static/index.81e5d079.js"></script>
  <link rel="modulepreload" href="/static/vendor.ba9c442b.js">
  <link rel="stylesheet" href="/static/index.f28d7853.css">
</head>
<body>
<div id="root"></div>

</body>
</html>

info: It is a spring boot app.

So how to fix the files' path?


Solution

  • Configure the base URL to be ./:

    // vite.config.js
    import { defineConfig } from 'vite'
    
    export default defineConfig({
      base: './', 👈
    })
    

    demo