├── .gitignore
├── README.md
├── demo
├── dist
│ ├── index.js
│ ├── styles-3275f665.css
│ ├── styles-3a3f9686.css
│ ├── styles-ef356b6d.css
│ ├── styles-eff1cae3.css
│ └── styles-f32a2851.css
├── dynamic-import.css
├── foo.js
├── index.js
├── src
│ ├── bar.js
│ └── styles.css
├── styles.css
└── template-string.css
├── index.js
├── package-lock.json
├── package.json
├── rollup.config.js
└── src
├── ast.js
└── utils.js
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Rollup-plugin-native-css-modules
2 |
3 | Use native CSS modules with import assertions in Rollup. This plugin is intended to be used if you want to use import assertions in your build _output_, either in browsers that already support it, or because you're using something like [es-module-shims](https://github.com/guybedford/es-module-shims) to support native CSS modules.
4 |
5 | This plugin does **not** transform any CSS module imports to JavaScript, it leaves the import statements and imports in tact.
6 |
7 | ## Example
8 |
9 | Checkout the example on [Stackblitz](https://stackblitz.com/edit/rollup-repro-fbdojc).
10 |
11 | Or take a look at the [example project](https://github.com/thepassle/css-example-project) for a more elaborate example.
12 |
13 | ### Input
14 |
15 | `src/index.js`:
16 | ```js
17 | import styles from './styles.css' assert { type: 'css' };
18 | ```
19 |
20 | ### Output:
21 |
22 | `dist/index.js`:
23 | ```js
24 | import styles from './styles-3275f665.css' assert { type: 'css' };
25 | ```
26 |
27 | ## Usage
28 |
29 | ```
30 | npm i -S rollup-plugin-native-css-modules
31 | ```
32 |
33 | ```js
34 | import css from 'rollup-plugin-native-css-modules';
35 |
36 | export default {
37 | input: 'index.js',
38 | output: {
39 | dir: 'dist',
40 | format: 'esm'
41 | },
42 | plugins: [
43 | css(),
44 | /**
45 | * Or:
46 | */
47 | css({
48 | transform: (code) => {
49 | // modify the CSS code, minify, post-process, etc
50 | return code;
51 | }
52 | })
53 | ]
54 | };
55 | ```
56 |
57 | ## Features
58 |
59 | At time of writing Rollup V3 supports import assertion syntax, however, Rollup will still try to parse any module that gets imported in your source code and expect it to be JavaScript. This will cause Rollup to throw an error, because it'll try to parse CSS files expecting it to be JavaScript. This plugin fixes that.
60 |
61 | ### Support
62 |
63 | This plugin supports:
64 |
65 | ```js
66 | import styles from './styles.css' assert { type: 'css' };
67 | import styles from 'bare-module-specifier/styles.css' assert { type: 'css' };
68 | import('./styles.css', { assert: { type: 'css'} });
69 | ```
70 |
71 | This plugin does NOT support:
72 | ```js
73 | import(`./styles-${i}.css`, { assert: { type: 'css'} });
74 | import('./styles-' + i + '.css', { assert: { type: 'css'} });
75 | ```
76 |
77 | The reason for this is that imports with dynamic variables are hard to statically analyze, because they rely on runtime code.
78 |
79 | External stylesheets are ignored:
80 | ```js
81 | import styles from 'http://styles.com/index.css' assert { type: 'css' };
82 | import styles from 'https://styles.com/index.css' assert { type: 'css' };
83 | ```
84 |
85 | Data uri's are also ignored.
86 |
87 | ### Deduplication
88 |
89 | This plugin also deduplicates imports for the same module. If `foo.js` and `bar.js` both import `my-styles.css`, only one CSS file will be output in the output directory, as opposed to two.
90 |
91 | ### Hashing
92 |
93 | CSS modules output by this plugin receive a hash based on the contents of the CSS file. E.g.:
94 |
95 | **input:**
96 | ```js
97 | import styles from './styles.css' assert { type: 'css' };
98 | ```
99 |
100 | **output:**
101 | ```js
102 | import styles from './styles-3275f665.css' assert { type: 'css' };
103 | ```
104 |
105 | ### Transform
106 |
107 | You can use the `transform` hook to modify the CSS that gets output to, for example, minify your CSS using a tool like [lightning CSS](https://lightningcss.dev/docs.html) or something like postcss.
108 |
109 |
110 | ```js
111 | import css from 'rollup-plugin-native-css-modules';
112 | import { transform } from 'lightningcss';
113 |
114 | export default {
115 | input: 'demo/index.js',
116 | output: {
117 | dir: 'demo/dist',
118 | format: 'esm'
119 | },
120 | plugins: [
121 | css({
122 | transform: (css) => transform({
123 | code: Buffer.from(css),
124 | minify: true
125 | }).code.toString()
126 | })
127 | ]
128 | };
129 | ```
130 |
131 |
132 | ## FAQ
133 |
134 | ### Polyfilling
135 |
136 | At the time of writing, browser support for import assertions is still low, so you're probably going to need to polyfill them. You can do this via [`es-module-shims`](https://github.com/guybedford/es-module-shims), note that you'll also need a polyfill for constructable stylesheets, which you can polyfill via [`construct-style-sheets-polyfill`](https://www.npmjs.com/package/construct-style-sheets-polyfill).
137 |
138 | ### Why are CSS files not combined and bundled?
139 |
140 | Because you can't. Consider the following example:
141 |
142 | ```
143 | my-app/
144 | ├─ index.js
145 | ├─ element-a.js
146 | ├─ element-b.js
147 | ├─ blue-styles.css
148 | ├─ red-styles.css
149 | ```
150 |
151 |
152 | index.js
153 |
154 | ```js
155 | import './element-a.js';
156 | import './element-b.js';
157 | ```
158 |
159 |
160 |
161 | element-a.js
162 |
163 | ```js
164 | import blueStyles from './blue-styles.css' assert { type: 'css' };
165 |
166 | class ElementA extends HTMLElement {
167 | constructor() {
168 | super();
169 | this.attachShadow({ mode: 'open' });
170 | this.shadowRoot.adoptedStyleSheets = [blueStyles];
171 | }
172 |
173 | connectedCallback() {
174 | this.shadowRoot.innerHTML = 'blue
';
175 | }
176 | }
177 |
178 | customElements.define('element-a', ElementA);
179 | ```
180 |
181 |
182 |
183 | element-b.js
184 |
185 | ```js
186 | import redStyles from './red-styles.css' assert { type: 'css' };
187 |
188 | class ElementB extends HTMLElement {
189 | constructor() {
190 | super();
191 | this.attachShadow({ mode: 'open' });
192 | this.shadowRoot.adoptedStyleSheets = [redStyles];
193 | }
194 |
195 | connectedCallback() {
196 | this.shadowRoot.innerHTML = 'red
';
197 | }
198 | }
199 |
200 | customElements.define('element-b', ElementB);
201 | ```
202 |
203 |
204 |
205 | blue-styles.css
206 |
207 | ```css
208 | h1 {
209 | color: blue;
210 | }
211 | ```
212 |
213 |
214 |
215 | red-styles.css
216 |
217 | ```css
218 | h1 {
219 | color: red;
220 | }
221 | ```
222 |
223 |
224 | Bundling this would lead to the following build output:
225 |
226 |
227 | bundle.js
228 |
229 | ```js
230 | import blueStyles from './styles-3275f665.css' assert { type: 'css' };
231 | import redStyles from './styles-3a3f9686.css' assert { type: 'css' };
232 |
233 | class ElementA extends HTMLElement {
234 | constructor() {
235 | super();
236 | this.attachShadow({ mode: 'open' });
237 | this.shadowRoot.adoptedStyleSheets = [blueStyles];
238 | }
239 |
240 | connectedCallback() {
241 | this.shadowRoot.innerHTML = 'blue
';
242 | }
243 | }
244 |
245 | customElements.define('element-a', ElementA);
246 |
247 | class ElementB extends HTMLElement {
248 | constructor() {
249 | super();
250 | this.attachShadow({ mode: 'open' });
251 | this.shadowRoot.adoptedStyleSheets = [redStyles];
252 | }
253 |
254 | connectedCallback() {
255 | this.shadowRoot.innerHTML = 'red
';
256 | }
257 | }
258 |
259 | customElements.define('element-b', ElementB);
260 | ```
261 |
262 |
263 |
264 | styles-3a3f9686.css
265 |
266 | ```css
267 | h1 {
268 | color: red;
269 | }
270 | ```
271 |
272 |
273 |
274 | styles-3275f665.css
275 |
276 | ```css
277 | h1 {
278 | color: blue;
279 | }
280 | ```
281 |
282 |
283 | If you would combine the CSS files for `blueStyles` and `redStyles` into one, and use that stylesheet in both components, it would lead to style clashes; you would only have red `
`s, instead of one blue `` for `` and one red `` for ``.
284 |
285 | To illustrate:
286 |
287 |
288 | bundle.js
289 |
290 | ```js
291 | import bundledStyles from './styles-f32a2851.css' assert { type: 'css' };
292 |
293 | class ElementA extends HTMLElement {
294 | constructor() {
295 | super();
296 | this.attachShadow({ mode: 'open' });
297 | this.shadowRoot.adoptedStyleSheets = [bundledStyles];
298 | }
299 |
300 | connectedCallback() {
301 | this.shadowRoot.innerHTML = 'blue
';
302 | }
303 | }
304 |
305 | customElements.define('element-a', ElementA);
306 |
307 | class ElementB extends HTMLElement {
308 | constructor() {
309 | super();
310 | this.attachShadow({ mode: 'open' });
311 | this.shadowRoot.adoptedStyleSheets = [bundledStyles];
312 | }
313 |
314 | connectedCallback() {
315 | this.shadowRoot.innerHTML = 'red
';
316 | }
317 | }
318 |
319 | customElements.define('element-b', ElementB);
320 | ```
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 | styles-f32a2851.css
329 |
330 | ```css
331 | h1 {
332 | color: blue;
333 | }
334 |
335 | h1 {
336 | color: red;
337 | }
338 | ```
339 |
340 |
--------------------------------------------------------------------------------
/demo/dist/index.js:
--------------------------------------------------------------------------------
1 | import styleSheet from './styles-3275f665.css' assert { type: 'css' };
2 | import fooStyles from './styles-3a3f9686.css' assert { type: 'css' };
3 | import styleSheet2 from './styles-ef356b6d.css' assert { type: 'css' };
4 |
5 | console.log(styleSheet);
6 |
7 | const foo = 1;
8 |
9 | console.log(styleSheet);
10 | console.log(styleSheet2);
11 | const bar = 2;
12 |
13 | const dynamic = await import('./styles-eff1cae3.css', { assert: { type: 'css' } });
14 |
15 | const dynamicWithVariables = await import(`./dynamic-${1}.css`, {
16 | assert: { type: 'css' },
17 | });
18 |
19 | const quux = '';
20 | const dynamicVariable = await import(quux, {
21 | assert: { type: 'css' },
22 | });
23 |
24 | const dynamicImportTemplateString = await import('./styles-f32a2851.css', { assert: { type: 'css' } });
25 |
26 | const externalHttps = await import('https://foo.com/index.css', { assert: { type: 'css' } });
27 | const externalHttp = await import('http://foo.com/index.css', { assert: { type: 'css' } });
28 | // const dataUri = await import('data:text/bla');
29 | const concatenatedStrings = await import('./my' + 1 + '.css', { assert: { type: 'css'} });
30 |
31 | console.log(concatenatedStrings);
32 | // console.log(dataUri);
33 | console.log(externalHttp);
34 | console.log(externalHttps);
35 | console.log(dynamicImportTemplateString);
36 | console.log(dynamicVariable);
37 | console.log(dynamicWithVariables);
38 | console.log(dynamic);
39 | console.log(bar);
40 | console.log(foo);
41 | console.log(styleSheet);
42 | console.log(fooStyles);
43 |
--------------------------------------------------------------------------------
/demo/dist/styles-3275f665.css:
--------------------------------------------------------------------------------
1 | body {
2 | border: solid 2px red;
3 | background: lavender;
4 | }
5 |
6 | body {
7 | border: solid 2px red;
8 | background: lavender;
9 | }
10 |
11 | body {
12 | border: solid 2px red;
13 | background: lavender;
14 | }
15 |
16 | body {
17 | border: solid 2px red;
18 | background: lavender;
19 | }
20 |
21 | body {
22 | border: solid 2px red;
23 | background: lavender;
24 | }
25 |
26 | body {
27 | border: solid 2px red;
28 | background: lavender;
29 | } .bar { color: red;}
--------------------------------------------------------------------------------
/demo/dist/styles-3a3f9686.css:
--------------------------------------------------------------------------------
1 | .foo {
2 | color: red;
3 | } .bar { color: red;}
--------------------------------------------------------------------------------
/demo/dist/styles-ef356b6d.css:
--------------------------------------------------------------------------------
1 | html {
2 | background: blue;
3 | } .bar { color: red;}
--------------------------------------------------------------------------------
/demo/dist/styles-eff1cae3.css:
--------------------------------------------------------------------------------
1 | .bla {
2 | color: green;
3 | } .bar { color: red;}
--------------------------------------------------------------------------------
/demo/dist/styles-f32a2851.css:
--------------------------------------------------------------------------------
1 | html {
2 | border: solid 2px red;
3 | } .bar { color: red;}
--------------------------------------------------------------------------------
/demo/dynamic-import.css:
--------------------------------------------------------------------------------
1 | .bla {
2 | color: green;
3 | }
--------------------------------------------------------------------------------
/demo/foo.js:
--------------------------------------------------------------------------------
1 | import styleSheet from './styles.css' assert { type: 'css' };
2 |
3 | console.log(styleSheet);
4 |
5 | export const foo = 1;
--------------------------------------------------------------------------------
/demo/index.js:
--------------------------------------------------------------------------------
1 | import styleSheet from './styles.css' assert { type: 'css' };
2 | import fooStyles from '@thepassle/css/foo.css' assert { type: 'css' };
3 | import { foo } from './foo.js';
4 | import { bar } from './src/bar.js';
5 |
6 | const dynamic = await import('./dynamic-import.css', {
7 | assert: { type: 'css' },
8 | });
9 |
10 | const dynamicWithVariables = await import(`./dynamic-${1}.css`, {
11 | assert: { type: 'css' },
12 | });
13 |
14 | const quux = '';
15 | const dynamicVariable = await import(quux, {
16 | assert: { type: 'css' },
17 | });
18 |
19 | const dynamicImportTemplateString = await import(`./template-string.css`, {
20 | assert: { type: 'css' },
21 | });
22 |
23 | const externalHttps = await import('https://foo.com/index.css', { assert: { type: 'css'} });
24 | const externalHttp = await import('http://foo.com/index.css', { assert: { type: 'css'} });
25 | // const dataUri = await import('data:text/bla');
26 | const concatenatedStrings = await import('./my' + 1 + '.css', { assert: { type: 'css'} });
27 |
28 | console.log(concatenatedStrings);
29 | // console.log(dataUri);
30 | console.log(externalHttp);
31 | console.log(externalHttps);
32 | console.log(dynamicImportTemplateString);
33 | console.log(dynamicVariable);
34 | console.log(dynamicWithVariables);
35 | console.log(dynamic);
36 | console.log(bar);
37 | console.log(foo);
38 | console.log(styleSheet);
39 | console.log(fooStyles);
40 |
--------------------------------------------------------------------------------
/demo/src/bar.js:
--------------------------------------------------------------------------------
1 | import styleSheet from '../styles.css' assert { type: 'css' };
2 | import styleSheet2 from './styles.css' assert { type: 'css' };
3 |
4 | console.log(styleSheet)
5 | console.log(styleSheet2)
6 | export const bar = 2;
--------------------------------------------------------------------------------
/demo/src/styles.css:
--------------------------------------------------------------------------------
1 | html {
2 | background: blue;
3 | }
--------------------------------------------------------------------------------
/demo/styles.css:
--------------------------------------------------------------------------------
1 | body {
2 | border: solid 2px red;
3 | background: lavender;
4 | }
5 |
6 | body {
7 | border: solid 2px red;
8 | background: lavender;
9 | }
10 |
11 | body {
12 | border: solid 2px red;
13 | background: lavender;
14 | }
15 |
16 | body {
17 | border: solid 2px red;
18 | background: lavender;
19 | }
20 |
21 | body {
22 | border: solid 2px red;
23 | background: lavender;
24 | }
25 |
26 | body {
27 | border: solid 2px red;
28 | background: lavender;
29 | }
--------------------------------------------------------------------------------
/demo/template-string.css:
--------------------------------------------------------------------------------
1 | html {
2 | border: solid 2px red;
3 | }
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | import path from 'path';
2 | import fs from 'fs/promises';
3 | import { createRequire } from 'module';
4 | import { asyncWalk } from 'estree-walker';
5 | import MagicString from 'magic-string';
6 |
7 | import {
8 | isStaticCssImport,
9 | isDynamicCssImport,
10 | isTemplateStringWithVariables,
11 | isBinaryExpression
12 | } from './src/ast.js';
13 | import { getSourceHash, isBareModuleSpecifier } from './src/utils.js';
14 |
15 | const require = createRequire(import.meta.url);
16 |
17 | const ignoredProtocols = ['data:', 'http:', 'https:'];
18 |
19 | /**
20 | * @param {{
21 | * transform?: (code: string) => string | Promise
22 | * }} options
23 | * @return {import('rollup').Plugin}
24 | */
25 | export default function css(options = {}) {
26 | const cssFilesMap = {};
27 |
28 | return {
29 | name: 'css',
30 | resolveId(id) {
31 | if (id.endsWith('.css')) {
32 | return {
33 | id,
34 | external: true
35 | }
36 | }
37 | },
38 | async transform(code, id) {
39 | if (!id.endsWith('.css')) {
40 | const ast = this.parse(code);
41 | const magicString = new MagicString(code);
42 | let modifiedCode = false;
43 |
44 | await asyncWalk(ast, {
45 | enter: async node => {
46 | if (
47 | isStaticCssImport(node) ||
48 | isDynamicCssImport(node)
49 | ) {
50 | if(
51 | /**
52 | * @example `import(`./foo-${i}.css`, { assert: { type: 'css'} })`
53 | */
54 | isTemplateStringWithVariables(node) ||
55 | /**
56 | * @example `import('./foo-' + i + '.css', { assert: { type: 'css'} })`
57 | */
58 | isBinaryExpression(node)
59 | ) {
60 | console.warn(`
61 | [ROLLUP-PLUGIN-NATIVE-CSS-MODULES]: Dynamic imports with variables are not supported, since they rely on runtime code they are hard to statically analyze.
62 |
63 | Found in module "${id}":
64 |
65 | ${code.substring(node.start, node.end)}
66 | `);
67 | return;
68 | }
69 |
70 | if(
71 | node.source.type !== 'Literal' &&
72 | node.source.type !== 'TemplateLiteral'
73 | ) {
74 | return;
75 | }
76 |
77 | const moduleSpecifier = /** @type {string} */ (node.source.value || node.source.quasis[0].value.raw);
78 |
79 | /** Ignore external css files or data URIs */
80 | if(ignoredProtocols.some(protocol => moduleSpecifier.startsWith(protocol))) {
81 | return;
82 | }
83 |
84 | const dirname = path.dirname(id);
85 | const absolutePathToCssModule = isBareModuleSpecifier(moduleSpecifier)
86 | ? require.resolve(moduleSpecifier)
87 | : path.join(dirname, moduleSpecifier);
88 |
89 | /** If we havent processed this file before */
90 | if (!cssFilesMap[absolutePathToCssModule]) {
91 | const cssModuleContentsBuffer = await fs.readFile(absolutePathToCssModule);
92 | const cssModuleContents = await cssModuleContentsBuffer.toString();
93 |
94 | const assetSource = options?.transform
95 | ? await options?.transform(cssModuleContents)
96 | : cssModuleContents;
97 |
98 | const hash = getSourceHash(assetSource);
99 | const assetName = `styles-${hash}.css`;
100 | cssFilesMap[absolutePathToCssModule] = assetName;
101 |
102 | this.emitFile({
103 | type: 'asset',
104 | fileName: assetName,
105 | source: assetSource
106 | });
107 |
108 | magicString.overwrite(
109 | node.source.start,
110 | node.source.end,
111 | `'./${assetName}'`
112 | );
113 |
114 | modifiedCode = true;
115 | } else {
116 | magicString.overwrite(
117 | node.source.start,
118 | node.source.end,
119 | `'./${cssFilesMap[absolutePathToCssModule]}'`
120 | );
121 |
122 | modifiedCode = true;
123 | }
124 | }
125 | }
126 | });
127 |
128 | if (modifiedCode) {
129 | return {
130 | code: magicString.toString(),
131 | map: magicString.generateMap({ hires: true }),
132 | };
133 | }
134 |
135 | return null;
136 | }
137 | }
138 | }
139 | }
140 |
141 |
--------------------------------------------------------------------------------
/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "rollup-css-modules",
3 | "version": "1.0.0",
4 | "lockfileVersion": 2,
5 | "requires": true,
6 | "packages": {
7 | "": {
8 | "name": "rollup-css-modules",
9 | "version": "1.0.0",
10 | "license": "ISC",
11 | "dependencies": {
12 | "estree-walker": "^3.0.3",
13 | "magic-string": "^0.27.0",
14 | "rollup": "^3.10.0"
15 | },
16 | "devDependencies": {
17 | "@thepassle/css": "^1.0.0"
18 | }
19 | },
20 | "node_modules/@jridgewell/sourcemap-codec": {
21 | "version": "1.4.14",
22 | "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz",
23 | "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw=="
24 | },
25 | "node_modules/@thepassle/css": {
26 | "version": "1.0.0",
27 | "resolved": "https://registry.npmjs.org/@thepassle/css/-/css-1.0.0.tgz",
28 | "integrity": "sha512-vss402ZC/Ivi5Z4APcKFcw3IZlsVQFDU4TFps9SZscRbKn11zaJbwuqKlZWJRd98DdV9P6MKD4xFv5nI2nhB1g==",
29 | "dev": true
30 | },
31 | "node_modules/@types/estree": {
32 | "version": "1.0.0",
33 | "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.0.tgz",
34 | "integrity": "sha512-WulqXMDUTYAXCjZnk6JtIHPigp55cVtDgDrO2gHRwhyJto21+1zbVCtOYB2L1F9w4qCQ0rOGWBnBe0FNTiEJIQ=="
35 | },
36 | "node_modules/estree-walker": {
37 | "version": "3.0.3",
38 | "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
39 | "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
40 | "dependencies": {
41 | "@types/estree": "^1.0.0"
42 | }
43 | },
44 | "node_modules/fsevents": {
45 | "version": "2.3.2",
46 | "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
47 | "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
48 | "hasInstallScript": true,
49 | "optional": true,
50 | "os": [
51 | "darwin"
52 | ],
53 | "engines": {
54 | "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
55 | }
56 | },
57 | "node_modules/magic-string": {
58 | "version": "0.27.0",
59 | "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.27.0.tgz",
60 | "integrity": "sha512-8UnnX2PeRAPZuN12svgR9j7M1uWMovg/CEnIwIG0LFkXSJJe4PdfUGiTGl8V9bsBHFUtfVINcSyYxd7q+kx9fA==",
61 | "dependencies": {
62 | "@jridgewell/sourcemap-codec": "^1.4.13"
63 | },
64 | "engines": {
65 | "node": ">=12"
66 | }
67 | },
68 | "node_modules/rollup": {
69 | "version": "3.10.1",
70 | "resolved": "https://registry.npmjs.org/rollup/-/rollup-3.10.1.tgz",
71 | "integrity": "sha512-3Er+yel3bZbZX1g2kjVM+FW+RUWDxbG87fcqFM5/9HbPCTpbVp6JOLn7jlxnNlbu7s/N/uDA4EV/91E2gWnxzw==",
72 | "bin": {
73 | "rollup": "dist/bin/rollup"
74 | },
75 | "engines": {
76 | "node": ">=14.18.0",
77 | "npm": ">=8.0.0"
78 | },
79 | "optionalDependencies": {
80 | "fsevents": "~2.3.2"
81 | }
82 | }
83 | },
84 | "dependencies": {
85 | "@jridgewell/sourcemap-codec": {
86 | "version": "1.4.14",
87 | "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz",
88 | "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw=="
89 | },
90 | "@thepassle/css": {
91 | "version": "1.0.0",
92 | "resolved": "https://registry.npmjs.org/@thepassle/css/-/css-1.0.0.tgz",
93 | "integrity": "sha512-vss402ZC/Ivi5Z4APcKFcw3IZlsVQFDU4TFps9SZscRbKn11zaJbwuqKlZWJRd98DdV9P6MKD4xFv5nI2nhB1g==",
94 | "dev": true
95 | },
96 | "@types/estree": {
97 | "version": "1.0.0",
98 | "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.0.tgz",
99 | "integrity": "sha512-WulqXMDUTYAXCjZnk6JtIHPigp55cVtDgDrO2gHRwhyJto21+1zbVCtOYB2L1F9w4qCQ0rOGWBnBe0FNTiEJIQ=="
100 | },
101 | "estree-walker": {
102 | "version": "3.0.3",
103 | "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
104 | "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
105 | "requires": {
106 | "@types/estree": "^1.0.0"
107 | }
108 | },
109 | "fsevents": {
110 | "version": "2.3.2",
111 | "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
112 | "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
113 | "optional": true
114 | },
115 | "magic-string": {
116 | "version": "0.27.0",
117 | "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.27.0.tgz",
118 | "integrity": "sha512-8UnnX2PeRAPZuN12svgR9j7M1uWMovg/CEnIwIG0LFkXSJJe4PdfUGiTGl8V9bsBHFUtfVINcSyYxd7q+kx9fA==",
119 | "requires": {
120 | "@jridgewell/sourcemap-codec": "^1.4.13"
121 | }
122 | },
123 | "rollup": {
124 | "version": "3.10.1",
125 | "resolved": "https://registry.npmjs.org/rollup/-/rollup-3.10.1.tgz",
126 | "integrity": "sha512-3Er+yel3bZbZX1g2kjVM+FW+RUWDxbG87fcqFM5/9HbPCTpbVp6JOLn7jlxnNlbu7s/N/uDA4EV/91E2gWnxzw==",
127 | "requires": {
128 | "fsevents": "~2.3.2"
129 | }
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "rollup-plugin-native-css-modules",
3 | "version": "1.1.1",
4 | "description": "",
5 | "main": "index.js",
6 | "type": "module",
7 | "scripts": {
8 | "build": "rollup -c rollup.config.js"
9 | },
10 | "keywords": [
11 | "native",
12 | "css",
13 | "modules",
14 | "import",
15 | "assertions",
16 | "rollup"
17 | ],
18 | "author": "Pascal Schilp ",
19 | "license": "ISC",
20 | "dependencies": {
21 | "estree-walker": "^3.0.3",
22 | "magic-string": "^0.27.0",
23 | "rollup": "^3.10.0"
24 | },
25 | "devDependencies": {
26 | "@thepassle/css": "^1.0.0"
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import css from './index.js';
2 |
3 | export default {
4 | input: 'demo/index.js',
5 | output: {
6 | dir: 'demo/dist',
7 | format: 'esm'
8 | },
9 | plugins: [
10 | css({
11 | transform: code => {
12 | return `${code} .bar { color: red;}`;
13 | }
14 | })
15 | ]
16 | };
--------------------------------------------------------------------------------
/src/ast.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @example import styles from './styles.css' assert { type: 'css' };
3 | * @param {import('estree-walker').Node} node
4 | * @returns {boolean}
5 | */
6 | export function isStaticCssImport(node) {
7 | return (
8 | node.type === 'ImportDeclaration' &&
9 | node.assertions?.length &&
10 | node.assertions.some(assertion => (
11 | assertion.key.name === 'type' &&
12 | assertion.value.value === 'css'
13 | ))
14 | )
15 | }
16 |
17 | /**
18 | * @example import('./styles.css', {assert: { type: 'css' }});
19 | * @param {import('estree-walker').Node} node
20 | * @returns {boolean}
21 | */
22 | export function isDynamicCssImport(node) {
23 | return (
24 | node.type === 'ImportExpression' &&
25 | node.arguments?.[0]?.properties?.[0]?.key?.name === 'assert' &&
26 | node.arguments?.[0]?.properties?.[0]?.value?.properties?.[0]?.key.name === 'type' &&
27 | node.arguments?.[0]?.properties?.[0]?.value?.properties?.[0]?.value?.value === 'css'
28 | )
29 | }
30 |
31 | /**
32 | * @example import(`./foo-${i}.css`, { assert: { type: 'css'} })
33 | * @param {import('estree-walker').Node} node
34 | * @returns {boolean}
35 | */
36 | export function isTemplateStringWithVariables(node) {
37 | return (
38 | node.source.type === 'TemplateLiteral' &&
39 | node.source?.quasis?.length > 1
40 | )
41 | }
42 |
43 | /**
44 | * @example import('./foo-' + i + '.css', { assert: { type: 'css'} })
45 | * @param {import('estree-walker').Node} node
46 | * @returns {boolean}
47 | */
48 | export function isBinaryExpression(node) {
49 | return node.source.type === 'BinaryExpression';
50 | }
--------------------------------------------------------------------------------
/src/utils.js:
--------------------------------------------------------------------------------
1 | import { createHash } from 'node:crypto';
2 |
3 | const DEFAULT_HASH_SIZE = 8;
4 |
5 | /**
6 | * @param {string} source
7 | * @returns {string}
8 | */
9 | export function getSourceHash(source) {
10 | return createHash('sha256').update(source).digest('hex').slice(0, DEFAULT_HASH_SIZE);
11 | }
12 |
13 | /**
14 | * @param {string} specifier
15 | * @returns {boolean}
16 | */
17 | export function isBareModuleSpecifier(specifier) {
18 | return !!specifier?.replace(/'/g, '')[0].match(/[@a-zA-Z]/g);
19 | }
--------------------------------------------------------------------------------