How can I assign a custom CSS file name when building a VITE application?
Asked Answered
N

3

8

Is it possible to build in VITE and use application-name.css or my-site-name.css?

VITE has an option to build a custom JS file, but not a custom CSS or SCSS file (for export).

https://vitejs.dev/guide/build.html#library-mode

VITE Build name: style.css

Nickerson answered 31/8, 2021 at 2:12 Comment(1)
Please provide enough code so others can better understand or reproduce the problem.Irs
R
26

This is my vite.config.js for have custom css file name:

   rollupOptions: {
      output: {
        assetFileNames: (assetInfo) => {
          if (assetInfo.name == 'style.css')
            return 'customname.css';
          return assetInfo.name;
        },
      }
Rags answered 25/9, 2021 at 15:47 Comment(3)
Thank you for the detailed code, work great, The vite can hander build simple easy Is it possible to build the style NOT minify? (for preview)Nickerson
Great answer for CSS, assetFileNames will handle assets such as CSS and SVG files. Other useful ones to know about are: dir, and entryFileNames and chunkFileNames for JS.Septuplet
can I move the generated style.css file to a css folder like return "css/style.css"?Janson
T
8

This seems more robust in latest versions. The current solution was not working for me originally.

build: {
    lib: {
      name: 'LIBRARYNAME',
      fileName: 'LIBRARYNAME',
    },
    rollupOptions: {
      output: {
        assetFileNames: "LIBRARYNAME.[ext]",
      },
    },
  },

This produces:

dist/LIBRARYNAME.css      
dist/LIBRARYNAME.cjs.js  
dist/LIBRARYNAME.cjs.js.map 
dist/LIBRARYNAME.umd.js   
dist/LIBRARYNAME.umd.js.map

Without name and filename, the JS files end up default names. Without the rollup option, the CSS file ends up style.css.

Toplevel answered 31/10, 2022 at 20:10 Comment(2)
This worked for me with [email protected]. As per vitejs.dev/config/build-options.html#build-lib if not specified the build.lib.fileName is derived from the name property in your package.json.Adkins
in the new version of vite like [email protected] it doesn't work. any suggestions?Balbur
H
4

I had to use index.css instead of style.css as vite was building me css with that name (prehash) and then apply the rollup.

so this worked for me:

in vite.config.js

/** @type {import('vite').UserConfig} */

export default {
  build: {
    rollupOptions: {
      output: {
        assetFileNames: (assetInfo) => {
          if (assetInfo.name == "index.css") return "css/styles.css";
          return assetInfo.name;
        },
      },
    },
  },
};

this also puts the css file in the new css folder inside the dist folder automatically.

Hedda answered 17/10, 2023 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.