├── .editorconfig ├── .gitignore ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── index.html ├── package-lock.json ├── package.json ├── public ├── data │ ├── info.json │ └── x.css ├── index.js ├── other.css ├── style.css └── test-el │ ├── test-el.wc.css │ └── test-el.wc.js ├── rollup.config.js ├── rollup.dev.cjs.config.js ├── rollup.dev.esm.config.js ├── src └── import-assert.ts └── tsconfig.json /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | insert_final_newline = true 7 | indent_style = space 8 | indent_size = 2 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | insert_final_newline = false 13 | trim_trailing_whitespace = false -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | dist 4 | lib 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | ### [3.0.1](https://github.com/calebdwilliams/rollup-plugin-import-assert/compare/v3.0.0...v3.0.1) (2023-05-04) 6 | 7 | ## [3.0.0](https://github.com/calebdwilliams/rollup-plugin-import-assert/compare/v2.1.3...v3.0.0) (2023-05-04) 8 | 9 | 10 | ### ⚠ BREAKING CHANGES 11 | 12 | * Bump deps because of rollup 3 13 | 14 | ### Features 15 | 16 | * upgrade to rollup 3 ([309e531](https://github.com/calebdwilliams/rollup-plugin-import-assert/commit/309e531288d2835e4bbcfddbccdb91eb7bcc7149)) 17 | 18 | ### [2.1.3](https://github.com/calebdwilliams/rollup-plugin-import-assert/compare/v2.1.2...v2.1.3) (2022-11-08) 19 | 20 | ### [2.1.2](https://github.com/calebdwilliams/rollup-plugin-import-assert/compare/v2.1.0...v2.1.2) (2022-10-27) 21 | 22 | ### [2.1.1](https://github.com/calebdwilliams/rollup-plugin-import-assert/compare/v2.1.0...v2.1.1) (2022-10-27) 23 | 24 | ## [2.1.0](https://github.com/calebdwilliams/rollup-plugin-import-assert/compare/v1.1.2...v2.1.0) (2022-01-05) 25 | 26 | 27 | ### Features 28 | 29 | * cjs and esm support ([dc11dc1](https://github.com/calebdwilliams/rollup-plugin-import-assert/commit/dc11dc1a5940c2e301e0b5a918c9e0ee2ae1e2d5)) 30 | * handle edgecases in dynamic imports ([b821aa6](https://github.com/calebdwilliams/rollup-plugin-import-assert/commit/b821aa623d23d317e35be629a76ac86401879787)) 31 | 32 | ### [1.1.2](https://github.com/calebdwilliams/rollup-plugin-import-assert/compare/v1.1.1...v1.1.2) (2022-01-04) 33 | 34 | ### [1.1.1](https://github.com/calebdwilliams/rollup-plugin-import-assert/compare/v1.1.0...v1.1.1) (2021-07-21) 35 | 36 | 37 | ### Bug Fixes 38 | 39 | * add keywords to package.json ([55cb627](https://github.com/calebdwilliams/rollup-plugin-import-assert/commit/55cb627bfd0f489acb715526ff91c352c4e5195e)) 40 | 41 | ## 1.1.0 (2021-07-21) 42 | 43 | 44 | ### Features 45 | 46 | * initial commit ([428e1d3](https://github.com/calebdwilliams/rollup-plugin-import-assert/commit/428e1d378a2f6c1aeb34dbf7207656e41aba450a)) 47 | 48 | 49 | ### Bug Fixes 50 | 51 | * properly escape temlate literals ([0223958](https://github.com/calebdwilliams/rollup-plugin-import-assert/commit/02239585e468acfc9ea7bd0f081748a0ebab10a1)) 52 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright 2021 Caleb Williams 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rollup-plugin-import-assert 2 | 3 | 🍣 A Rollup plugin which enables [import assertions](https://github.com/tc39/proposal-import-assertions) for top-level CSS and JSON modules. 4 | 5 | ## Installation 6 | 7 | This package is available on the npm registry under the name `rollup-plugin-import-assert` and can be installed with npm, yarn or however else you consume dependencies. 8 | 9 | ### Example commands 10 | 11 | npm: 12 | 13 | ```zsh 14 | npm i -D rollup-plugin-import-assert 15 | ``` 16 | 17 | yarn: 18 | 19 | ```zsh 20 | yarn add -D rollup-plugin-import-assert 21 | ``` 22 | 23 | ## Usage 24 | 25 | Once the plugin is installed, you will also need to make sure you have the `acorn-import-assertions` package installed. You can then add both items to your Rollup configuration as below: 26 | 27 | ```javascript 28 | import { importAssertionsPlugin } from 'rollup-plugin-import-assert'; 29 | import { importAssertions } from 'acorn-import-assertions'; 30 | 31 | export default { 32 | input: 'path/to/file.js' 33 | output: { 34 | format: 'esm', 35 | dir: 'lib' // only necessary to enable dynamic imports 36 | }, 37 | acornInjectPlugins: [ importAssertions ], 38 | plugins: [ importAssertionsPlugin() ] 39 | } 40 | ``` 41 | 42 | These two plugins will enable the import assertion syntax and behavior in your Rollup build. In your input file, you can import files using type assertions as follows: 43 | 44 | ```javascript 45 | import styles from './styles.css' assert { type: 'css' }; 46 | 47 | class MyCustomElement extends HTMLElement { 48 | connectedCallback() { 49 | const root = this.attachShadow({ mode: 'open' }); 50 | root.innerHTML = `

Hello world

`; 51 | root.adoptedStyleSheets = [ styles ]; 52 | } 53 | } 54 | 55 | customElements.define('my-custom-element', MyCustomElement); 56 | ``` 57 | 58 | Assuming valid CSS in `styles.css`, the contents of the the CSS will be transformed to use CSS module scripts for use with `DocumentOrShadowRoot.prototype.adoptedStyleSheets`. Currently this API only exists in Chrome, but a [polyfill exists](https://www.npmjs.com/package/construct-style-sheets-polyfill) to port the behavior back to IE11. 59 | 60 | ## Limitations 61 | 62 | This plugin will ignore dynamic imports with dynamic values, e.g.: 63 | 64 | ```js 65 | import(`./foo/${bar}.json`, { assert: { type: 'json' } }); // will be ignored 66 | 67 | const foo = './foo.json'; 68 | import(foo, { assert: { type: 'json' } }); // will be ignored 69 | ``` -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Test page 5 | 6 | 7 | 8 | 9 | 10 | 11 |

Hello world

12 |

It works

13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rollup-plugin-import-assert", 3 | "version": "3.0.1", 4 | "description": "A Rollup plugin to add import assertion behavior and syntax support", 5 | "main": "dist/import-assert.js", 6 | "module": "dist/import-assert.js", 7 | "type": "module", 8 | "exports": { 9 | "require": "./dist/import-assert.cjs", 10 | "import": "./dist/import-assert.js" 11 | }, 12 | "scripts": { 13 | "build": "tsc && rollup -c rollup.config.js", 14 | "postrelease": "git push --follow-tags origin main && npm publish", 15 | "prepack": "npm run build", 16 | "release": "standard-version", 17 | "start": "rollup -c rollup.dev.esm.config.js", 18 | "start:cjs": "rollup -c rollup.dev.cjs.config.js" 19 | }, 20 | "keywords": [ 21 | "Rollup", 22 | "constructible stylesheets", 23 | "json", 24 | "css", 25 | "web components", 26 | "acorn" 27 | ], 28 | "author": "Caleb D. Williams ", 29 | "repository": "github:calebdwilliams/rollup-plugin-import-assert", 30 | "license": "MIT", 31 | "dependencies": { 32 | "string-to-template-literal": "^2.0.0" 33 | }, 34 | "devDependencies": { 35 | "@rollup/plugin-commonjs": "^23.0.7", 36 | "@rollup/plugin-node-resolve": "^15.0.1", 37 | "@types/node": "^18.11.17", 38 | "acorn-import-assertions": "^1.8.0", 39 | "ava": "^5.1.0", 40 | "rollup": "^3.7.5", 41 | "standard-version": "^9.5.0", 42 | "typescript": "^4.9.4" 43 | }, 44 | "peerDependencies": { 45 | "acorn-import-assertions": "^1.8.0", 46 | "rollup": "^3.0.0" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /public/data/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": { 3 | "first": "Caleb", 4 | "last": "Williams" 5 | }, 6 | "wroteThis": true 7 | } -------------------------------------------------------------------------------- /public/data/x.css: -------------------------------------------------------------------------------- 1 | h1 { color: lemonchiffon; } -------------------------------------------------------------------------------- /public/index.js: -------------------------------------------------------------------------------- 1 | import styles from './style.css' assert { type: 'css' }; 2 | import data from './data/info.json' assert { type: 'json' }; 3 | import './test-el/test-el.wc.js'; 4 | 5 | document.adoptedStyleSheets = [styles]; 6 | 7 | setTimeout(() => { 8 | document.querySelector('h1 > span').innerText = data.name.first; 9 | }, 1000); 10 | 11 | import('./other.css', { assert: { type: 'css' } }) 12 | .then(module => { 13 | const sheet = module.default; 14 | document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]; 15 | }); 16 | -------------------------------------------------------------------------------- /public/other.css: -------------------------------------------------------------------------------- 1 | h2 { 2 | color: rebeccapurple; 3 | } 4 | -------------------------------------------------------------------------------- /public/style.css: -------------------------------------------------------------------------------- 1 | * { 2 | color: tomato; 3 | } -------------------------------------------------------------------------------- /public/test-el/test-el.wc.css: -------------------------------------------------------------------------------- 1 | .foo { 2 | color: royalblue; 3 | font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; 4 | } 5 | -------------------------------------------------------------------------------- /public/test-el/test-el.wc.js: -------------------------------------------------------------------------------- 1 | // import styles from './test-el.wc.css' assert { type: 'css' }; 2 | 3 | const template = document.createElement('template'); 4 | template.innerHTML = `TestEl, after clicking this button, the text should be blue 5 | `; 6 | 7 | class TestEl extends HTMLElement { 8 | constructor() { 9 | super(); 10 | const root = this.attachShadow({ mode: 'open' }); 11 | this.addStyles = this.addStyles.bind(this); 12 | } 13 | 14 | connectedCallback() { 15 | const content = template.content.cloneNode(true); 16 | 17 | this.shadowRoot.append(content); 18 | this.shadowRoot.querySelector('button').addEventListener('click', this.addStyles); 19 | } 20 | 21 | addStyles(event) { 22 | import('./test-el.wc.css', { assert: { type: 'css' }}) 23 | .then(module => module.default) 24 | .then(sheet => this.shadowRoot.adoptedStyleSheets = [ sheet ]); 25 | event.target.removeEventListener('click', this.addStyles); 26 | event.target.remove(); 27 | } 28 | } 29 | 30 | customElements.define('test-el', TestEl); 31 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import { nodeResolve } from '@rollup/plugin-node-resolve'; 2 | import commonjs from '@rollup/plugin-commonjs'; 3 | 4 | export default { 5 | input: 'dist/import-assert.js', 6 | output: { 7 | format: 'cjs', 8 | file: 'dist/import-assert.cjs' 9 | }, 10 | plugins: [ 11 | nodeResolve({ 12 | preferBuiltins: true 13 | }), 14 | commonjs() 15 | 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /rollup.dev.cjs.config.js: -------------------------------------------------------------------------------- 1 | const { importAssertions } = require('acorn-import-assertions'); 2 | const { importAssertionsPlugin } = require('./dist/import-assert.cjs'); 3 | 4 | module.exports = { 5 | input: 'public/index.js', 6 | output: { 7 | format: 'esm', 8 | dir: 'lib' 9 | }, 10 | acornInjectPlugins: [importAssertions], 11 | plugins: [ 12 | importAssertionsPlugin() 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /rollup.dev.esm.config.js: -------------------------------------------------------------------------------- 1 | import { importAssertions } from 'acorn-import-assertions'; 2 | import { importAssertionsPlugin } from './dist/import-assert.js'; 3 | 4 | export default { 5 | input: 'public/index.js', 6 | output: { 7 | format: 'esm', 8 | dir: 'lib' 9 | }, 10 | acornInjectPlugins: [importAssertions], 11 | plugins: [ 12 | importAssertionsPlugin() 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /src/import-assert.ts: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | import { Plugin } from 'rollup'; 3 | import convert from 'string-to-template-literal'; 4 | 5 | function getObjects(obj: any, key: string, val: string): any[] { 6 | let objects = []; 7 | 8 | for (let prop in obj) { 9 | if (!obj.hasOwnProperty(prop)) { 10 | continue; 11 | } 12 | if (typeof obj[prop] == 'object') { 13 | objects = objects.concat(getObjects(obj[prop], key, val)); 14 | } else 15 | 16 | if (prop == key && obj[prop] == val || prop == key && val == '') { // 17 | objects.push(obj); 18 | } else if (obj[prop] == val && key == ''){ 19 | if (objects.lastIndexOf(obj) == -1){ 20 | objects.push(obj); 21 | } 22 | } 23 | } 24 | return objects; 25 | } 26 | 27 | type Assertion = { type: 'css'|'json' }; 28 | 29 | const assertionMap = new Map(); 30 | const filePattern = /\.(js|ts|jsx|tsx)$/; 31 | 32 | const getImportPath = (id: string, source: string): string => path.resolve(path.dirname(id), source); 33 | 34 | export function importAssertionsPlugin(): Plugin { 35 | return { 36 | name: 'rollup-plugin-import-assert', 37 | transform(data: string, id: string) { 38 | let code = data; 39 | /** If the file is a JS-like file, continue */ 40 | if (filePattern.exec(id)) { 41 | /** Get the AST data, must be using acorn-import-assertions for this to work */ 42 | const ast = this.parse(data); 43 | 44 | /** @ts-ignore this does exist apparently */ 45 | const { body } = ast; 46 | const importDeclarations = getObjects(body, 'type', 'ImportDeclaration'); 47 | const importExpressions = getObjects(body, 'type', 'ImportExpression'); 48 | 49 | importDeclarations.forEach(node => { 50 | if (node.assertions) { 51 | const [ assertion ] = node.assertions as any; 52 | const assert: Assertion = { type: assertion.value.value }; 53 | const importPath = getImportPath(id, node.source.value); 54 | assertionMap.set(importPath, assert); 55 | } 56 | }); 57 | 58 | importExpressions.forEach(node => { 59 | // Skip dynamic imports with expressions 60 | // @example: import(`./foo/${bar}.js`); // NOK 61 | // @example: import(`./foo/bar.js`); // OK 62 | if(node.source.type === "TemplateLiteral" && node.source.quasis.length > 1) { 63 | return; 64 | } 65 | 66 | // @example: `import(foo);` NOK 67 | if(!node.source.value) return; 68 | 69 | const source = node.source.value || node.source.quasis[0].value.raw; 70 | const importPath = getImportPath(id, source); 71 | 72 | // TODO: We can still make this better 73 | if (node.hasOwnProperty('arguments') && getObjects(node, 'name', 'assert')) { 74 | const assert: Assertion = { type: node.arguments[0].properties[0]?.value?.properties[0].value.value }; 75 | assertionMap.set(importPath, assert); 76 | 77 | const matches = code.match(/import\(.*\)/gi); 78 | const replacements = matches.map(match => match.replace(/\{(\s?)assert:(\s?)\{.*\}/gi, '')); 79 | 80 | if (matches) { 81 | matches.forEach((match, index) => 82 | code = code.replace(match, replacements[index]) 83 | ); 84 | 85 | code.match(/import\(.*(\s?),(\s?)\)/gi).forEach(match => { 86 | code = code.replace(match, 87 | match.replace(',', '') 88 | ); 89 | }); 90 | } 91 | } 92 | }); 93 | } 94 | 95 | const assertion = assertionMap.get(id); 96 | 97 | /** If an import assertion exists for the file, parse it differently */ 98 | if (assertion) { 99 | const { type } = assertion; 100 | let code = data; 101 | 102 | if (type === 'css') { 103 | /** Parse files asserted as CSS to use constructible stylesheets */ 104 | code = `const sheet = new CSSStyleSheet();sheet.replaceSync(${convert(data)});export default sheet;`; 105 | } else if (type === 'json') { 106 | /** Parse files asserted as JSON as a JS object */ 107 | code = `export default ${data}`; 108 | } 109 | 110 | /** Return the new data */ 111 | return { code, map: {mappings: ""} }; 112 | } 113 | 114 | /** If none of the above exists, just continue as normal */ 115 | return { code, map: null }; 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": true, 4 | "allowSyntheticDefaultImports": true, 5 | "target": "ESNext", 6 | "declaration": true, 7 | "declarationDir": "dist", 8 | "moduleResolution": "node", 9 | "outDir": "dist", 10 | "rootDir": "src" 11 | }, 12 | "lib": ["dom", "ESNext"], 13 | "include": ["./src/**/*"], 14 | "exclude": ["node_modules", "dist"] 15 | } 16 | --------------------------------------------------------------------------------