Inject CSS at the top of chunk files in Vite library mode using import statements, supporting multiple entries.
npx @tessl/cli install tessl/npm-vite-plugin-lib-inject-css@2.2.00
# Vite Plugin Lib Inject CSS
1
2
Vite Plugin Lib Inject CSS automatically injects CSS import statements at the top of generated JavaScript chunk files in Vite library mode builds. It solves the common problem of associating CSS styles with component libraries, enabling automatic style imports without manual intervention while maintaining SSR compatibility.
3
4
## Package Information
5
6
- **Package Name**: vite-plugin-lib-inject-css
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install vite-plugin-lib-inject-css -D`
10
11
## Core Imports
12
13
```typescript
14
import { libInjectCss } from 'vite-plugin-lib-inject-css';
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { libInjectCss } = require('vite-plugin-lib-inject-css');
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { defineConfig } from 'vite';
27
import { libInjectCss } from 'vite-plugin-lib-inject-css';
28
29
export default defineConfig({
30
plugins: [
31
libInjectCss(),
32
],
33
build: {
34
lib: {
35
entry: 'src/index.ts',
36
formats: ['es']
37
}
38
}
39
});
40
```
41
42
## Architecture
43
44
The plugin works by:
45
46
1. **Configuration Enhancement**: Automatically sets required Vite options (`cssCodeSplit: true`, `ssrEmitAssets: true`, `hoistTransitiveImports: false`)
47
2. **AST Analysis**: Uses `@ast-grep/napi` to parse JavaScript and find optimal injection points after imports and expression statements
48
3. **CSS Discovery**: Leverages Vite's internal `chunk.viteMetadata.importedCss` to identify CSS files associated with each chunk
49
4. **Import Injection**: Adds appropriate import statements (`import './style.css';` for ES modules, `require('./style.css');` for CommonJS) at the top of chunks
50
5. **Source Map Preservation**: Maintains source maps when enabled using `magic-string`
51
52
## Capabilities
53
54
### Plugin Factory Function
55
56
Creates a Vite plugin instance that handles CSS injection in library builds.
57
58
```typescript { .api }
59
/**
60
* Inject css at the top of each generated chunk file, only works with library mode.
61
* @returns Vite Plugin object configured for CSS injection
62
*/
63
function libInjectCss(): Plugin;
64
```
65
66
**Usage Examples:**
67
68
```typescript
69
import { defineConfig } from 'vite';
70
import { libInjectCss } from 'vite-plugin-lib-inject-css';
71
72
// Basic single-entry configuration
73
export default defineConfig({
74
plugins: [libInjectCss()],
75
build: {
76
lib: {
77
entry: 'src/index.ts',
78
formats: ['es']
79
}
80
}
81
});
82
83
// Multi-entry configuration
84
export default defineConfig({
85
plugins: [libInjectCss()],
86
build: {
87
lib: {
88
formats: ['es', 'cjs'],
89
entry: {
90
index: 'src/index.ts',
91
button: 'src/components/button/index.ts',
92
select: 'src/components/select/index.ts',
93
}
94
},
95
rollupOptions: {
96
output: {
97
chunkFileNames: 'chunks/[name].[hash].js',
98
assetFileNames: 'assets/[name][extname]',
99
entryFileNames: '[name].js',
100
},
101
},
102
}
103
});
104
```
105
106
## Plugin Configuration Behavior
107
108
The plugin automatically configures several Vite options:
109
110
### CSS Code Splitting
111
112
```typescript { .api }
113
// Automatically set by the plugin
114
build: {
115
cssCodeSplit: true // Required for CSS injection to work
116
}
117
```
118
119
### SSR Asset Emission
120
121
```typescript { .api }
122
// Automatically set by the plugin
123
build: {
124
ssrEmitAssets: true // Required for SSR builds
125
}
126
```
127
128
### Transitive Imports Hoisting
129
130
```typescript { .api }
131
// Automatically set by the plugin (can be overridden)
132
rollupOptions: {
133
output: {
134
hoistTransitiveImports: false // Prevents tree-shaking issues
135
}
136
}
137
```
138
139
## Types
140
141
```typescript { .api }
142
interface Plugin {
143
name: string;
144
apply: 'build';
145
enforce: 'post';
146
config(config: UserConfig): Partial<UserConfig>;
147
configResolved(config: ResolvedConfig): void;
148
options(): void;
149
generateBundle(opts: OutputOptions, bundle: OutputBundle): void;
150
}
151
152
// From Vite types
153
interface ResolvedConfig {
154
build: {
155
lib?: LibBuildOptions;
156
ssr?: boolean;
157
ssrEmitAssets?: boolean;
158
sourcemap?: boolean;
159
};
160
command: 'build' | 'serve';
161
}
162
163
interface OutputOptions {
164
format: 'es' | 'cjs' | 'umd' | 'iife';
165
}
166
167
interface OutputBundle {
168
[fileName: string]: OutputAsset | OutputChunk;
169
}
170
171
interface UserConfig {
172
build?: {
173
lib?: LibBuildOptions;
174
cssCodeSplit?: boolean;
175
ssrEmitAssets?: boolean;
176
rollupOptions?: {
177
output?: {
178
hoistTransitiveImports?: boolean;
179
chunkFileNames?: string;
180
assetFileNames?: string;
181
entryFileNames?: string;
182
};
183
};
184
};
185
}
186
187
interface LibBuildOptions {
188
entry: string | string[] | { [key: string]: string };
189
formats?: ('es' | 'cjs' | 'umd' | 'iife')[];
190
}
191
192
interface OutputAsset {
193
type: 'asset';
194
fileName: string;
195
source: string | Uint8Array;
196
}
197
198
interface OutputChunk {
199
type: 'chunk';
200
fileName: string;
201
code: string;
202
map?: any;
203
viteMetadata?: {
204
importedCss: Set<string>;
205
};
206
}
207
```
208
209
## Operating Requirements
210
211
The plugin has specific operating requirements:
212
213
- **Library Mode Only**: Must be used with Vite's library mode (`build.lib` configured)
214
- **Build Command Only**: Only operates during build process (`command === 'build'`)
215
- **CSS Code Split**: Requires `cssCodeSplit: true` (automatically set)
216
- **SSR Assets**: For SSR builds, requires `ssrEmitAssets: true` (automatically set)
217
218
## Error Handling and Warnings
219
220
The plugin provides console warnings for common configuration issues:
221
222
- Warns when not in library mode or building process
223
- Alerts about SSR configuration conflicts that may cause injection failures
224
- Uses colored console output for better visibility
225
226
## Generated Output Format
227
228
The plugin generates different import formats based on the output format:
229
230
```javascript
231
// For ES modules (format: 'es')
232
import './assets/component.css';
233
// ... rest of chunk code
234
235
// For CommonJS (format: 'cjs')
236
require('./assets/component.css');
237
// ... rest of chunk code
238
```
239
240
CSS file paths are automatically calculated as relative paths from the chunk location to the CSS file location.