Skip to content

Commit

Permalink
fix(kv-components): include import line for component css files
Browse files Browse the repository at this point in the history
  • Loading branch information
emuvente committed Jan 22, 2025
1 parent cb46aba commit 46cf73a
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
59 changes: 59 additions & 0 deletions @kiva/kv-components/build/libCss.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { writeFileSync } from 'node:fs';
import {
basename,
dirname,
relative,
resolve,
} from 'node:path';

let viteConfig;

export default function libCss() {
return {
name: 'lib-css',
apply: 'build',
enforce: 'post',

// Get Vite config when it's resolved to use later
configResolved(config) {
viteConfig = config;
},

// Write css import statements to files with imported css after bundle is created
writeBundle(option, bundle) {
// Only run for es format in library mode
if (!viteConfig.build?.lib || option.format !== 'es') {
return;
}

const { root } = viteConfig;
const { outDir } = viteConfig.build;
const cssReplaceRegex = /\/\* empty css \s*\*\//;
const files = Object.keys(bundle);

// Find files with imported css
const filesWithImportedCss = files.filter((file) => bundle[file].viteMetadata?.importedCss?.size > 0);

// Replace empty css comment with css import statement in each file
filesWithImportedCss.forEach((file) => {
if (bundle[file].viteMetadata.importedCss.size > 1) {
console.warn(`Multiple css file imports not supported yet, skipping ${file}`);
return;
}

// Get css import path relative to current file
const [cssPath] = bundle[file].viteMetadata.importedCss;
const cssImportPath = relative(dirname(file), cssPath);

// Add prefix for current directory to css import path if necessary
const prefix = cssImportPath === basename(cssPath) ? './' : '';

// Replace empty css comment with css import statement
const fileContent = bundle[file].code.replace(cssReplaceRegex, `import "${prefix}${cssImportPath}";`);

// Write updated file content
writeFileSync(resolve(root, outDir, file), fileContent);
});
},
};
}
3 changes: 3 additions & 0 deletions @kiva/kv-components/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { defineConfig } from 'vite';
import libAssetsPlugin from '@laynezh/vite-plugin-lib-assets'
import noBundlePlugin from 'vite-plugin-no-bundle';
import vue from '@vitejs/plugin-vue';
import libCss from './build/libCss';

export default defineConfig({
resolve: {
Expand Down Expand Up @@ -54,5 +55,7 @@ export default defineConfig({
outputPath: 'kvui',
publicUrl: 'https://www.kiva.org/',
}),
// Ensure component css is imported into the final build
libCss(),
],
});

0 comments on commit 46cf73a

Please sign in to comment.