Skip to content

CSS imports #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ node_modules
# Build files
dist
/test/**/output.*
/test/**/output/
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
"scripts": {
"build": "rollup -c",
"dev": "rollup -cw",
"test:simple": "cd test/simple && rm -f output.* && rollup -c && cmp output.js ../expected.js && cmp output.css expected.css && cd ../..",
"test": "npm run test:simple",
"test:nested": "cd test/nested && rm -rf output && rollup -c && cmp output/bundle.js expected/bundle.js && cmp output/bundle.css expected/bundle.css && cd ../..",
"test:simple": "cd test/simple && rm -rf output && rollup -c && cmp output/output.js expected.js && cmp output/output.css expected.css && cd ../..",
"test:imports": "cd test/imports && rm -rf output && rollup -c && cmp output/bundle.js expected/bundle.js && cmp output/bundle.css expected/bundle.css && cd ../..",
"test": "npm run test:simple && npm run test:nested && npm run test:imports",
"lint": "prettier rollup.config.js src/**",
"prepare": "npm run build",
"prepublish": "npm run build"
Expand Down
117 changes: 97 additions & 20 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,130 @@
import { createFilter } from '@rollup/pluginutils'

var arraysEqual = function(a, b) {
if (a.length !== b.length) return false

for (let i = a.length; i--;) {
if (a[i] !== b[i]) return false
}

return true
}

function splitImports(code) {
const imports = [];
const codeWithoutImports = code.replace(/@import\s+(.*);(\r\n)+/gm, (_, group) => {
imports.push(group.replace(/(["'])~/, '$1'));
return '';
});
return {
imports,
codeWithoutImports
};
}

// Get all CSS modules in the order that they were imported
function getCSSModules(id, getModuleInfo) {
const modules = [];
const visited = new Set();

// traversal logic
// 1. mark node as visited
// 2. add to list at the end
// 3. go down with imports but in reverse order
// 4. reverse full list
// example
// root
// 1
// 11
// 12
// 2
// 21
// 22
// will result in the list: root, 2, 22, 21, 1, 12, 11
// revered: 11, 12, 1, 21, 22, 2, root
const visitModule = (id) => {
if (visited.has(id)) {
return;
}
visited.add(id);
if (filter(id)) {
modules.push(id);
}
const reverseChildren = getModuleInfo(id).importedIds.slice().reverse();
reverseChildren.forEach(visitModule);
}
visitModule(id);
return modules.reverse();
};

export default function css(options = {}) {
const filter = createFilter(options.include || ['**/*.css'], options.exclude)
const styles = {}
const order = []
let dest = options.output
let changes = 0
let hasChanged = false
let prevIds = []

return {
name: 'css',
buildStart() {
hasChanged = false
},
transform(code, id) {
if (!filter(id)) {
return
}

const { imports, codeWithoutImports } = splitImports(code);

// When output is disabled, the stylesheet is exported as a string
if (options.output === false) {
if (imports.length === 0) {
return {
code: `export default ['${JSON.stringify(code)}'`,
map: { mappings: '' }
}
}
const importNamed = imports.map((d, i) => `import i${i} from ${d}`).join('\n');
return {
code: 'export default ' + JSON.stringify(code),
code: `
${importNamed}
export default ${imports.map((_, i) => `i${i}`).join(' + ')} + '${JSON.stringify(codeWithoutImports)}'`,
map: { mappings: '' }
}
}

// Track the order that each stylesheet is imported.
if (!order.includes(id)) {
order.push(id)
}

// Keep track of every stylesheet
// Check if it changed since last render
if (styles[id] !== code && (styles[id] || code)) {
styles[id] = code
changes++
// NOTE: If we are in transform block, we can assume styles[id] !== code, right?
if (styles[id] !== codeWithoutImports && (styles[id] || codeWithoutImports)) {
styles[id] = codeWithoutImports
hasChanged = true
}

return ''
// return a list of imports
return imports.map((d) => `import ${d}`).join('\n');
},
generateBundle(opts, bundle) {
// No stylesheet needed
if (!changes || options.output === false) {
return
const ids = []

// Determine import order of files
for (const file in bundle) {
const root = bundle[file].facadeModuleId
const modules = getCSSModules(root, this.getModuleInfo)
ids.push(...modules)
}
changes = 0

// Combine all stylesheets, respecting import order
// If the files are imported in the same order and there are no changes
// or options.output is false, there is no work to be done
if (arraysEqual(prevIds, ids) && !hasChanged || options.output === false) return
prevIds = ids

let css = ''
for (let x = 0; x < order.length; x++) {
const id = order[x]
css += styles[id] || ''

// Combine all stylesheets, respecting import order
for (const index in ids) {
let id = ids[index]
css += styles[id] + '\n' || ''
}

// Emit styles through callback
Expand Down
3 changes: 3 additions & 0 deletions test/imports/css/first.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.first {
color: blue;
}
5 changes: 5 additions & 0 deletions test/imports/css/input.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
@import './second.css';

.last {
color: green;
}
5 changes: 5 additions & 0 deletions test/imports/css/second.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
@import './fist.css';

.second {
color: green;
}
12 changes: 12 additions & 0 deletions test/imports/expected/bundle.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.first {
color: blue;
}

.second {
color: green;
}

.last {
color: green;
}

File renamed without changes.
3 changes: 3 additions & 0 deletions test/imports/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import './css/input.css'

console.log('css imported')
12 changes: 12 additions & 0 deletions test/imports/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import css from '../../src/index.js'

export default {
input: 'input.js',
output: {
file: 'output/bundle.js',
format: 'esm'
},
plugins: [
css({ output: 'bundle.css' })
]
}
2 changes: 2 additions & 0 deletions test/nested/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
## Test Case
This is to test that nested imports are bundled in the proper order
3 changes: 3 additions & 0 deletions test/nested/css/b.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
background-color: blue;
}
3 changes: 3 additions & 0 deletions test/nested/css/g.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
background-color: green;
}
3 changes: 3 additions & 0 deletions test/nested/css/r.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
background-color: red;
}
9 changes: 9 additions & 0 deletions test/nested/expected/bundle.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
body {
background-color: blue;
}
body {
background-color: red;
}
body {
background-color: green;
}
3 changes: 3 additions & 0 deletions test/nested/expected/bundle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
console.log('This should happen first');

console.log('This should happen second');
5 changes: 5 additions & 0 deletions test/nested/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import './js/b.js';
import './css/r.css';
import './css/g.css';

console.log('This should happen second');
3 changes: 3 additions & 0 deletions test/nested/js/b.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import '../css/b.css';

console.log('This should happen first');
12 changes: 12 additions & 0 deletions test/nested/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import css from '../../src/index.js'

export default {
input: 'input.js',
output: {
file: 'output/bundle.js',
format: 'esm'
},
plugins: [
css({ output: 'bundle.css' })
]
}
File renamed without changes.
2 changes: 1 addition & 1 deletion test/input.css → test/simple/input.css
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.rollup {
color: green;
user-select: none;
}
}
File renamed without changes.
6 changes: 3 additions & 3 deletions test/simple/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import css from '../../src/index.js'

export default {
input: '../input.js',
input: 'input.js',
output: {
file: 'output.js',
file: 'output/output.js',
format: 'esm'
},
plugins: [
css()
css({ output: 'output.css' })
]
}