I am building a library for a Website with Typescript and vite that exports one Main class. That class needs a Json file for the constructor and that Json file includes multiple URLs to assets like Images or Videos. These URLs are imported using this bit of code for further Processing inside the library:
export function getMedia(url:string){
let newURL = new URL(`${url}`, import.meta.url).href;
return newURL;
}
I want to use this library for a Website. I import the main class from this library and use the constructor with a Json that is located inside the Project. The URLs inside this Json also Point so assets that are located inside the Project. The Json looks something like this:
{
"mediaFiles": [
{
"id": 1,
"type": "Texture",
"url": "/src/assets/situations/thumbnails/thumbnail1.jpg"
},
{
"id": 2,
"type": "Texture",
"url": "/src/assets/situations/thumbnails/thumbnail12.jpg"
},
{
"id": 3,
"type": "Texture",
"url": "/src/assets/situations/thumbnails/thumbnail13.jpg"
},
....
]
}
The structure of my website project looks like this:
Project Root
│ index.html
│ package-lock.json
│ package.json
│ README.md
│ tsconfig.json
│ vite.config.ts
│
└───src
│ main.ts
│
└───assets
│ exampleConfig.json
│
└───situations
│
└───thumbnails
thumbnail1.jpg
thumbnail2.jpg
thumbnail3.jpg
In my main.ts I import the main class from the library and I pass the “exampleConfig.json” into its constructor. The urls inside this json point to the src/assets folder e.g. “/src/assets/situations/thumbnails/thumbnail11.jpg”.
The Problem I am facing is when I build the Website using vite the assets are not included inside the dist folder. When I preview the build vite wont convert the paths of the media files so they still point to /src/assets/… and the assets are therefore not found. When I use the vite development Server everything is working fine.
This is my vite.config.mts:
import { resolve} from "path";
import { defineConfig } from 'vite';
export default defineConfig({
resolve: {
alias: {
'@': resolve(__dirname, './src')
}
},
build: {
sourcemap: true,
rollupOptions: {
output: {
chunkFileNames: 'assets/js/[name]-[hash].js', // js files in "js" folder
entryFileNames: 'assets/js/[name]-[hash].js',
// Change directory of build files
assetFileNames: ({name}) => {
if (/.(gif|jpe?g|png|svg|webp|avif)$/.test(name ?? '')) //Images in "images" folder
return 'assets/images/[name]-[hash][extname]';
if (/.(mp4|webm)$/.test(name ?? '')) // videos in "videos" folder
return 'assets/videos/[name]-[hash][extname]';
if (/.css$/.test(name ?? '')) // css in "css" folder
return 'assets/css/[name]-[hash][extname]';
if (/.(glb|env|gltf|ktx2|bin)$/.test(name ?? '')) // glb in "3DData" folder
return 'assets/3DData/[name]-[hash][extname]';
if (/.pdf$/.test(name ?? '')) // pdf in "pdfs" folder
return 'assets/pdfs/[name]-[hash][extname]';
if (/.json$/.test(name ?? '')) // json in "json" folder
return 'assets/json/[name]-[hash][extname]';
return 'assets/other/[name]-[hash][extname]';
},
},
}
},
})