Ad

Vite - Change Static Assets' Directoy

- 1 answer

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.


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 have also changed output's directory.

After runing npm run build, all 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.jsIt 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>

The backend is a spring boot app.

So how to fix the files' path?

Ad

Answer

Configure the base URL to be ./:

// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  base: './', πŸ‘ˆ
})

demo

Ad
source: stackoverflow.com
Ad