1+ import fs from 'fs' ;
2+ import path from 'path' ;
3+ import { fileURLToPath } from 'url' ;
4+
15import resolve from '@rollup/plugin-node-resolve' ;
26import commonjs from '@rollup/plugin-commonjs' ;
37import typescript from '@rollup/plugin-typescript' ;
48import dts from 'rollup-plugin-dts' ;
59import { terser } from 'rollup-plugin-terser' ;
610import babel from '@rollup/plugin-babel' ;
711import postcss from 'rollup-plugin-postcss' ;
12+ import postcssInlineUrl from 'postcss-url' ;
813import wyw from '@wyw-in-js/rollup' ;
14+ import postcssProcessor from 'postcss' ;
915
1016import { createRequire } from 'module' ;
1117
@@ -22,6 +28,9 @@ const external = [
2228 ...Object . keys ( devDependencies ) ,
2329] ;
2430
31+ const __filename = fileURLToPath ( import . meta. url ) ;
32+ const __dirname = path . dirname ( __filename ) ;
33+
2534export default [
2635 {
2736 input : {
@@ -83,6 +92,63 @@ export default [
8392 ] ,
8493 } ) ,
8594 terser ( ) ,
95+ {
96+ name : 'postcss-svg-inline' ,
97+ async writeBundle ( ) {
98+ const cssFile = path . resolve ( __dirname , 'dist/index.css' ) ;
99+
100+ if ( ! fs . existsSync ( cssFile ) ) return ;
101+ const css = fs . readFileSync ( cssFile , 'utf8' ) ;
102+
103+ // Custom PostCSS plugin to handle CSS custom properties with local file paths
104+ const customInlinePlugin = {
105+ postcssPlugin : 'custom-inline-svg' ,
106+ async Declaration ( decl ) {
107+ if ( decl . value && decl . value . includes ( 'url(' ) ) {
108+ // Find all url() patterns in the declaration value
109+ const urlRegex = / u r l \( ( [ ^ ) ] + ) \) / g;
110+ let match ;
111+ let newValue = decl . value ;
112+
113+ while ( ( match = urlRegex . exec ( decl . value ) ) !== null ) {
114+ const urlPath = match [ 1 ] . replace ( / [ ' " ] / g, '' ) ;
115+
116+ // Check if it's a local file path
117+ if ( urlPath . startsWith ( '/' ) && urlPath . includes ( '.svg' ) ) {
118+ try {
119+ const fullPath = path . resolve ( __dirname , urlPath ) ;
120+ if ( fs . existsSync ( fullPath ) ) {
121+ const svgContent = fs . readFileSync ( fullPath , 'utf8' ) ;
122+ const encodedSvg = encodeURIComponent ( svgContent ) ;
123+ const dataUrl = `data:image/svg+xml,${ encodedSvg } ` ;
124+
125+ // Replace the url() with the data URL
126+ newValue = newValue . replace ( match [ 0 ] , `url("${ dataUrl } ")` ) ;
127+ }
128+ } catch ( error ) {
129+ console . warn ( `Failed to inline SVG: ${ urlPath } ` , error . message ) ;
130+ }
131+ }
132+ }
133+
134+ decl . value = newValue ;
135+ }
136+ }
137+ } ;
138+
139+ const result = await postcssProcessor ( [
140+ customInlinePlugin ,
141+ postcssInlineUrl ( {
142+ url : 'inline' ,
143+ encodeType : 'encodeURIComponent' ,
144+ maxSize : Infinity ,
145+ filter : '**/*.svg' ,
146+ } )
147+ ] ) . process ( css , { from : cssFile , to : cssFile } ) ;
148+
149+ fs . writeFileSync ( cssFile , result . css ) ;
150+ }
151+ } ,
86152 ] ,
87153 external
88154 } ,
0 commit comments