├── .gitignore ├── .eslintrc.js ├── LICENSE ├── package.json ├── README.md ├── CHANGELOG.md ├── tsconfig.json └── index.ts /.gitignore: -------------------------------------------------------------------------------- 1 | # npm 2 | node_modules 3 | package-lock.json 4 | 5 | # output 6 | index.js 7 | index.d.ts 8 | 9 | # MacOS 10 | .DS_Store 11 | 12 | # IntelliJ 13 | .idea 14 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parser: '@typescript-eslint/parser', 4 | plugins: [ 5 | '@typescript-eslint', 6 | ], 7 | extends: [ 8 | 'eslint:recommended', 9 | 'plugin:@typescript-eslint/recommended', 10 | ], 11 | }; 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 Fábio Domingues 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. 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rollup-plugin-css-chunks", 3 | "version": "2.0.3", 4 | "description": "Rollup plugin to extract CSS into chunks", 5 | "main": "index.js", 6 | "files": [ 7 | "index.js", 8 | "index.d.ts", 9 | "README.md", 10 | "LICENSE" 11 | ], 12 | "scripts": { 13 | "build": "tsc", 14 | "lint": "eslint index.ts", 15 | "prepublishOnly": "npm run lint" 16 | }, 17 | "repository": "domingues/rollup-plugin-css-chunks", 18 | "keywords": [ 19 | "rollup-plugin", 20 | "css" 21 | ], 22 | "author": "Fábio Domingues", 23 | "license": "MIT", 24 | "bugs": { 25 | "url": "https://github.com/domingues/rollup-plugin-css-chunks/issues" 26 | }, 27 | "homepage": "https://github.com/domingues/rollup-plugin-css-chunks", 28 | "dependencies": { 29 | "rollup-pluginutils": "^2.7.1", 30 | "sourcemap-codec": "^1.4.4", 31 | "url-join": "^4.0.1" 32 | }, 33 | "devDependencies": { 34 | "@types/node": "^14.10.3", 35 | "@types/url-join": "^4.0.0", 36 | "@typescript-eslint/eslint-plugin": "^4.1.1", 37 | "@typescript-eslint/parser": "^4.1.1", 38 | "eslint": "^7.9.0", 39 | "rollup": "^2.29.0", 40 | "typescript": "^4.0.2" 41 | }, 42 | "peerDependencies": { 43 | "rollup": ">=2.29.0" 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rollup-plugin-css-chunks 2 | 3 | [Rollup](https://github.com/rollup/rollup) plugin to extract imported CSS files as chunks, allowing code split of CSS 4 | stylesheets. Use [rollup-plugin-extract-bundle-tree](https://github.com/domingues/rollup-plugin-extract-bundle-tree) to 5 | extract dependencies between JS and CSS chunks. 6 | 7 | ## Installation 8 | 9 | ```bash 10 | npm install --save-dev rollup-plugin-css-chunks 11 | ``` 12 | 13 | ## Features 14 | 15 | - Split CSS in chunks; 16 | - Load CSS map referenced or embedded on `sourceMappingURL`; 17 | - Return CSS chunk public URL; 18 | 19 | ## Usage 20 | 21 | ```javascript 22 | import css_chunk_url from './home.css'; 23 | 24 | const css_chunk_map_url = css_chunk_url + '.map'; 25 | console.log({css_chunk_url, css_chunk_map_url}) 26 | ``` 27 | 28 | ## Configuration 29 | 30 | ```js 31 | // rollup.config.js 32 | import css from 'rollup-plugin-css-chunks'; 33 | 34 | export default { 35 | input: 'src/main.js', 36 | output: { 37 | dir: 'public', 38 | format: 'esm' 39 | }, 40 | plugins: [ 41 | css({ 42 | // inject a CSS `@import` directive for each chunk depended on 43 | injectImports: false, 44 | // name pattern for emitted secondary chunks 45 | chunkFileNames: '[name]-[hash].css', 46 | // name pattern for emitted entry chunks 47 | entryFileNames: '[name].css', 48 | // public base path of the files 49 | publicPath: '', 50 | // generate sourcemap 51 | sourcemap: false, 52 | // emit css/map files 53 | emitFiles: true, 54 | }) 55 | ] 56 | } 57 | ``` 58 | 59 | ## License 60 | 61 | MIT 62 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # rollup-plugin-css-chunks changelog 2 | 3 | ## 2.0.3 (03/03/2021) 4 | 5 | * fix: invalid RegEx ([#21](https://github.com/domingues/rollup-plugin-css-chunks/pull/21)); 6 | 7 | ## 2.0.2 (10/12/2020) 8 | 9 | * fix: peerDependencies specification (#17); 10 | 11 | ## 2.0.1 (07/12/2020) 12 | 13 | * fix: url-join missing from dependencies (#13); 14 | 15 | ## 2.0.0 (07/12/2020) 16 | 17 | * feat: load source map file of `sourceMappingURL`; 18 | * feat: return CSS chunk public URL; 19 | * fix: no-treeshake causing inclusion of dead CSS and "phantom" js modules (#7); 20 | 21 | ## 1.2.9 (30/11/2020) 22 | 23 | * build: add type definitions. 24 | 25 | ## 1.2.8 (21/09/2020) 26 | 27 | * Fix build. 28 | 29 | ## 1.2.7 (20/09/2020) 30 | 31 | * Fix `entryFileNames`; 32 | * Use TypeScript. 33 | 34 | ## 1.2.6 (09/09/2020) 35 | 36 | * Use the chunk name rather than `chunk`. 37 | 38 | ## 1.2.5 (08/09/2020) 39 | 40 | * Fix `@import` injection. 41 | 42 | ## 1.2.4 (07/09/2020) 43 | 44 | * Add support to Rollup 2 ([#2](https://github.com/domingues/rollup-plugin-css-chunks/pull/2)); 45 | * Fix Rollup 2 deprecation warning [[#3](https://github.com/domingues/rollup-plugin-css-chunks/issues/3)]. 46 | 47 | ## 1.2.3 (12/08/2019) 48 | 49 | * Fix bug when parsing sourcemaps with non ASCII characters. 50 | 51 | ## 1.2.2 (08/07/2019) 52 | 53 | * Fix bug that generates source maps even when disabled. 54 | 55 | ## 1.2.1 (04/07/2019) 56 | 57 | * Don't break source maps when imported CSS files don't have them. 58 | 59 | ## 1.2.0 (21/05/2019) 60 | 61 | * Move imports from `bundle[].assetImports` to `bundle[].imports`. 62 | 63 | ## 1.1.3 (11/04/2019) 64 | 65 | * Fixed bug when find assets chunks; 66 | * Readme updated. 67 | 68 | ## 1.1.2 (10/04/2019) 69 | 70 | * Change `bundle[].assetsImports` to `bundle[].assetImports`. 71 | 72 | ## 1.1.1 (10/04/2019) 73 | 74 | * Readme updated. 75 | 76 | ## 1.1.0 (10/04/2019) 77 | 78 | * Chunks file names based on their own content hash; 79 | * Options to set entry point and chunk file names structure; 80 | * Option to just consume CSS files, and don't produce any output; 81 | * Injection of `@import` directives are now disable by default; 82 | * Fix bug when files don't have source map data; 83 | * Inserted CSS imports on `bundle[].assetsImports` rollup bundle field. 84 | 85 | ## 1.0.0 (09/04/2019) 86 | 87 | * First release. 88 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Basic Options */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | "target": "es2019", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 8 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 9 | // "lib": [], /* Specify library files to be included in the compilation. */ 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 13 | "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | // "outDir": "./", /* Redirect output structure to the directory. */ 18 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 | // "removeComments": true, /* Do not emit comments to output. */ 22 | // "noEmit": true, /* Do not emit outputs. */ 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | 27 | /* Strict Type-Checking Options */ 28 | "strict": true, /* Enable all strict type-checking options. */ 29 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 30 | // "strictNullChecks": true, /* Enable strict null checks. */ 31 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 32 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 33 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 34 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 35 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 36 | 37 | /* Additional Checks */ 38 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 39 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 40 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 41 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 42 | 43 | /* Module Resolution Options */ 44 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 45 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 46 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 47 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 48 | // "typeRoots": [], /* List of folders to include type definitions from. */ 49 | // "types": [], /* Type declaration files to be included in compilation. */ 50 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 51 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 52 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 53 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 54 | 55 | /* Source Map Options */ 56 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 59 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 60 | 61 | /* Experimental Options */ 62 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 63 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 64 | 65 | /* Advanced Options */ 66 | "skipLibCheck": true, /* Skip type checking of declaration files. */ 67 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | import crypto from 'crypto'; 3 | import { 4 | NormalizedOutputOptions, 5 | OutputBundle, 6 | OutputChunk, 7 | PluginContext, 8 | PluginImpl, 9 | SourceMap, 10 | SourceMapInput 11 | } from 'rollup'; 12 | import {createFilter} from 'rollup-pluginutils'; 13 | import {encode, decode} from 'sourcemap-codec'; 14 | import {readFileSync} from "fs"; 15 | import urljoin from 'url-join'; 16 | 17 | function hash(content: string) { 18 | return crypto.createHmac('sha256', content) 19 | .digest('hex') 20 | .substr(0, 8); 21 | } 22 | 23 | function makeFileName(name: string, hashed: string, pattern: string) { 24 | return pattern.replace('[name]', name).replace('[hash]', hashed); 25 | } 26 | 27 | interface InputPluginOptions { 28 | injectImports?: boolean; 29 | chunkFileNames?: string; 30 | entryFileNames?: string; 31 | publicPath?: string; 32 | sourcemap?: boolean; 33 | emitFiles?: boolean; 34 | } 35 | 36 | const defaultPluginOptions = { 37 | injectImports: false, 38 | chunkFileNames: '[name]-[hash].css', 39 | entryFileNames: '[name].css', 40 | publicPath: '', 41 | sourcemap: false, 42 | emitFiles: true 43 | }; 44 | 45 | const cssChunks: PluginImpl = function (options = {}) { 46 | const filter = createFilter(/\.css$/i, []); 47 | 48 | Object.keys(options).forEach(key => { 49 | if (!(key in defaultPluginOptions)) 50 | throw new Error(`unknown option ${key}`); 51 | }); 52 | const pluginOptions = Object.assign({}, defaultPluginOptions, options); 53 | 54 | const css_data: Record = {}; 58 | 59 | return { 60 | name: 'css', 61 | 62 | load(id: string) { 63 | if (!filter(id)) return null; 64 | 65 | let code = readFileSync(id, 'utf8'); 66 | let map: SourceMapInput = null; 67 | 68 | let m = code.match(/\/\*#\W*sourceMappingURL=data:application\/json;charset=utf-8;base64,([a-zA-Z0-9+/]+)\W*\*\//); 69 | if (m !== null) { 70 | code = code.replace(m[0], '').trim(); 71 | try { 72 | map = JSON.parse(Buffer.from(m[1], 'base64').toString('utf-8').trim()); 73 | } catch (err) { 74 | console.warn(`Could not load css map file of ${id}.\n ${err}`); 75 | } 76 | } 77 | m = code.match(/\/\*#\W*sourceMappingURL=([^\\/]+)\W*\*\//); 78 | if (m !== null) { 79 | code = code.replace(m[0], '').trim(); 80 | try { 81 | map = readFileSync(path.resolve(id, '..', m[1].trim()), 'utf8'); 82 | } catch (err) { 83 | console.warn(`Could not load css map file of ${id}.\n ${err}`); 84 | } 85 | } 86 | 87 | return {code, map} 88 | }, 89 | 90 | transform(code: string, id: string) { 91 | if (!filter(id)) return null; 92 | css_data[id] = {code, map: this.getCombinedSourcemap()}; 93 | return {code: `export default import.meta.CSS_URL;`, map: null, meta: {transformedByCSSChunks: true}}; 94 | }, 95 | 96 | resolveImportMeta(property, options) { 97 | if (property == 'CSS_URL') { 98 | return `"CSS_FILE_${options.chunkId}"`; 99 | } 100 | return null; 101 | }, 102 | 103 | generateBundle(this: PluginContext, generateBundleOpts: NormalizedOutputOptions, bundle: OutputBundle) { 104 | let emitFiles = pluginOptions.emitFiles; 105 | if (!generateBundleOpts.dir) { 106 | this.warn('No directory provided. Skipping CSS generation'); 107 | emitFiles = false; 108 | } 109 | 110 | for (const chunk of Object.values(bundle).reverse()) { 111 | if (chunk.type === 'asset') continue; 112 | 113 | let code = ''; 114 | 115 | if (pluginOptions.injectImports) { 116 | for (const c of chunk.imports) { 117 | if (bundle[c]) { 118 | code += (bundle[c]).imports.filter(filter) 119 | .map(f => `@import '${f}';`).join(''); 120 | } 121 | } 122 | if (code != '') 123 | code += '\n'; 124 | } 125 | 126 | const css_modules: string[] = [] 127 | for (const f of Object.keys(chunk.modules)) { 128 | this.getModuleInfo(f)?.importedIds 129 | ?.filter(v => this.getModuleInfo(v)?.meta.transformedByCSSChunks == true) 130 | .forEach(v => css_modules.push(v)); 131 | } 132 | 133 | const sources = []; 134 | const sourcesContent = []; 135 | const mappings = []; 136 | for (const f of css_modules) { 137 | if (pluginOptions.sourcemap && emitFiles) { 138 | const i = sources.length; 139 | sources.push(...css_data[f].map.sources.map( 140 | source => path.relative(generateBundleOpts.dir ? generateBundleOpts.dir : '', source))); 141 | if (css_data[f].map.sourcesContent) { 142 | sourcesContent.push(...css_data[f].map.sourcesContent); 143 | } 144 | const decoded = decode(css_data[f].map.mappings); 145 | if (i === 0) { 146 | decoded[0].forEach(segment => { 147 | segment[0] += code.length; 148 | }); 149 | } 150 | if (i > 0) { 151 | decoded.forEach(line => { 152 | line.forEach(segment => { 153 | segment[1] = i; 154 | }); 155 | }); 156 | } 157 | mappings.push(...decoded); 158 | } 159 | code += css_data[f].code + '\n'; 160 | } 161 | 162 | if (code === '') continue; 163 | 164 | const css_file_name = makeFileName(chunk.name, hash(code), 165 | chunk.isEntry ? pluginOptions.entryFileNames : pluginOptions.chunkFileNames); 166 | 167 | const css_file_url = urljoin(pluginOptions.publicPath, css_file_name); 168 | chunk.code = chunk.code.replace(new RegExp(`CSS_FILE_${chunk.fileName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`, 'g'), css_file_url); 169 | 170 | if (emitFiles) { 171 | if (emitFiles && pluginOptions.sourcemap) { 172 | let map = null; 173 | const map_file_name = css_file_name + '.map'; 174 | map = { 175 | version: 3, 176 | file: css_file_name, 177 | sources: sources, 178 | sourcesContent: sourcesContent, 179 | names: [], 180 | mappings: encode(mappings) 181 | }; 182 | code += `/*# sourceMappingURL=${encodeURIComponent(map_file_name)} */`; 183 | this.emitFile({ 184 | type: 'asset', 185 | fileName: map_file_name, 186 | source: JSON.stringify(map, null) 187 | }); 188 | } 189 | this.emitFile({ 190 | type: 'asset', 191 | fileName: css_file_name, 192 | source: code 193 | }); 194 | chunk.imports.push(css_file_name); 195 | } 196 | } 197 | } 198 | }; 199 | }; 200 | 201 | export default cssChunks; 202 | --------------------------------------------------------------------------------