Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Vite - compile assets copying the source structure

2
by DamsFX, last modified on December 7th, 2024

When compiling theme assets with Vite, the assets are all stored in the themes\mytheme\assets\dist folder.

The result folder structure is :

themes/mytheme
├─ assets
│   ├─ dist
│   │   ├─ manifest.json
│   │   ├─ theme-mytheme-xxxxx.css
│   │   └─ theme-mytheme-xxxxx.js
│   ├─ src
│   │   ├─ css
|   │   │   └─ theme-mytheme.css
│   │   └─ js
|   │       └─ theme-mytheme.js

If you want the dist folder to mimic the src one, you can update your vite.confg.mjs file to add the following :

build: {
    outDir: 'assets/dist',
    assetsDir: '',
    rollupOptions: {
        output: {
            assetFileNames: ({name}) => {
                let extType = name.split('.').at(1);
                if (/\.css$/.test(name ?? '')) {
                    extType = 'css';
                }
                if (/\.(gif|jpe?g|png|svg|ico)$/.test(name ?? '')) {
                    extType = 'images';
                }
                if (/.(woff|woff2|eot|ttf)/.test(name ?? '')) {
                    extType = 'fonts';
                }
                return `${extType}/[name]-[hash][extname]`;
            },
            chunkFileNames: 'js/[name]-[hash].js',
            entryFileNames: 'js/[name]-[hash].js',
        },
    },
},
experimental: {
    renderBuiltUrl: function (filename, { hostId, hostType, type }) {
        if (type === 'asset') {
            if (hostType === 'css') {
                return filename.replace(/(?<type>images|fonts)/i, '../$<type>');
            }
        }
    }
},

The result folder structure will become :

themes/mytheme
├─ assets
│   ├─ dist
|   │   ├─ css
│   │   │   └─  theme-mytheme-xxxxx.css
|   │   ├─ js
│   │   │   └─ theme-mytheme-xxxxx.js
│   │   └─  manifest.json
│   ├─ src
│   │   ├─ css
|   │   |   └─ theme-mytheme.css
│   │   ├─ js
|   │   |   └─ theme-mytheme.js

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?