Skip to content

Postcss as a loader #3

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

Merged
merged 11 commits into from
Aug 4, 2015
Merged
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
83 changes: 12 additions & 71 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,19 @@
'use strict';

if (global._cssModulesPolyfill) {
throw new Error('only one instance of css-modules/polyfill is allowed');
}

global._cssModulesPolyfill = true;

var assign = require('object-assign');
var options = {};
var path = require('path');

/**
* Posibility to pass custom options to the module
* @param {object} opts
*/
module.exports = function (opts) {
assign(options, opts);
var escape = function (str) {
return str.replace(/[\[\]\/{}()*+?.\\^$|-]/g, '\\$&');
};

var Core = require('css-modules-loader-core');
var pluginsCache;

/**
* Caching plugins for the future calls
* @return {array}
*/
function loadPlugins() {
// retrieving from cache if they are already loaded
if (pluginsCache) {
return pluginsCache;
}

// PostCSS plugins passed to FileSystemLoader
var plugins = options.use || options.u;
if (!plugins) {
plugins = Core.defaultPlugins;
} else {
if (typeof plugins === 'string') {
plugins = [ plugins ];
}

plugins = plugins.map(function requirePlugin (name) {
// assume functions are already required plugins
if (typeof name === 'function') {
return name;
}

var plugin = require(require.resolve(name));
var regexp = ['src', 'test'].map(function (i) {
return '^' + escape(path.join(__dirname, i) + path.sep);
}).join('|');

// custom scoped name generation
if (name === 'postcss-modules-scope') {
options[name] = options[name] || {};
options[name].generateScopedName = createScopedNameFunc(plugin);
}
require('babel/register')({
only: new RegExp('(' + regexp + ')'),
ignore: false,
loose: 'all'
});

if (name in options) {
plugin = plugin(options[name]);
} else {
plugin = plugin.postcss || plugin();
}

return plugin;
});
}

return pluginsCache = plugins;
}

var FileSystemLoader = require('css-modules-loader-core/lib/file-system-loader');
var path = require('path');

require.extensions['.css'] = function (m, filename) {
var plugins = loadPlugins();
var loader = new FileSystemLoader(path.dirname(filename), plugins);
var tokens = loader.fetchSync(path.basename(filename), '/');

return m._compile('module.exports = ' + JSON.stringify(tokens), filename);
};
module.exports = require('./src');
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@
"description": "A require hook to compile CSS Modules on the fly",
"main": "index.js",
"dependencies": {
"babel": "^5.6.14",
"object-assign": "^3.0.0"
"babel": "^5.8.20",
"css-modules-loader-core": "0.0.11",
"postcss": "^4.1.16",
"postcss-modules-extract-imports": "0.0.5",
"postcss-modules-local-by-default": "0.0.9",
"postcss-modules-scope": "0.0.8"
},
"devDependencies": {
"mocha": "^2.2.5"
},
"scripts": {
"clone": "git clone https://github.com/sullenor/css-modules-loader-core.git node_modules/css-modules-loader-core",
"deps": "cd node_modules/css-modules-loader-core && npm i",
"postinstall": "npm run clone && npm run deps",
"preinstall": "rm -rf node_modules/css-modules-loader-core",
"test": "mocha test"
"test": "mocha --compilers js:babel/register"
},
"repository": {
"type": "git",
Expand Down
7 changes: 7 additions & 0 deletions src/guard.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use strict';

if (global._cssModulesPolyfill) {
throw new Error('only one instance of css-modules/polyfill is allowed');
}

global._cssModulesPolyfill = true;
11 changes: 11 additions & 0 deletions src/hook.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';

/**
* @param {function} compile
*/
module.exports = function (compile) {
require.extensions['.css'] = function (m, filename) {
var tokens = compile(filename);
return m._compile('module.exports = ' + JSON.stringify(tokens), filename);
};
};
68 changes: 68 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
'use strict';

import './guard';
import hook from './hook';
import postcss from 'postcss';
import { basename, dirname, join, resolve } from 'path';
import { readFileSync } from 'fs';

import extractImports from 'postcss-modules-extract-imports';
import localByDefault from 'postcss-modules-local-by-default';
import scope from 'postcss-modules-scope';
import parser from './parser';

let plugins = [localByDefault, extractImports, scope];

const load = (sourceString, sourcePath, trace, pathFetcher) => {
let exportTokens = {};
let result = postcss(plugins.concat(new parser({ exportTokens, pathFetcher, trace })))
.process(sourceString, {from: '/' + sourcePath})
.stringify();

return { injectableSource: result.css, exportTokens: exportTokens };
}

hook(filename => {
const root = dirname(filename);
const sources = {};
const tokensByFile = {};
let importNr = 0;

const fetch = (_newPath, _relativeTo, _trace) => {
let newPath = _newPath.replace(/^["']|["']$/g, '');
let trace = _trace || String.fromCharCode(importNr++);

let relativeDir = dirname(_relativeTo);
let rootRelativePath = resolve(relativeDir, newPath);
let fileRelativePath = resolve(join(root, relativeDir), newPath);

const tokens = tokensByFile[fileRelativePath];
if (tokens) {
return tokens;
}

let source = readFileSync(fileRelativePath, 'utf-8');
let { injectableSource, exportTokens } = load(source, rootRelativePath, trace, fetch);

sources[trace] = injectableSource;
tokensByFile[fileRelativePath] = exportTokens;

return exportTokens;
}

return fetch(basename(filename), '/');
});

/**
* @param {object} opts
* @param {array} opts.u
* @param {array} opts.use
*/
export default function configure(opts) {
opts = opts || {};

let customPlugins = opts.u || opts.use;
plugins = Array.isArray(customPlugins)
? customPlugins
: [localByDefault, extractImports, scope];
}
66 changes: 66 additions & 0 deletions src/parser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
'use strict';

import { plugin } from 'postcss';

const importRegexp = /^:import\((.+)\)$/

export default plugin('parser', function (opts) {
opts = opts || {};

let exportTokens = opts.exportTokens;
let translations = {};

const fetchImport = (importNode, relativeTo, depNr) => {
let file = importNode.selector.match( importRegexp )[1];
let depTrace = opts.trace + String.fromCharCode(depNr);
let exports = opts.pathFetcher(file, relativeTo, depTrace);

importNode.each(decl => {
if (decl.type === 'decl') {
translations[decl.prop] = exports[decl.value];
}
});

importNode.removeSelf();
}

const fetchAllImports = css => {
let imports = 0;

css.each(node => {
if (node.type === 'rule' && node.selector.match(importRegexp)) {
fetchImport(node, css.source.input.from, imports++);
}
});
}

const linkImportedSymbols = css => css.eachDecl(decl => {
Object.keys(translations).forEach(translation => {
decl.value = decl.value.replace(translation, translations[translation])
});
});

const handleExport = exportNode => {
exportNode.each(decl => {
if (decl.type === 'decl') {
Object.keys(translations).forEach(translation => {
decl.value = decl.value.replace(translation, translations[translation])
});

exportTokens[decl.prop] = decl.value;
}
});

exportNode.removeSelf();
}

const extractExports = css => css.each(node => {
if (node.type === 'rule' && node.selector === ':export') handleExport(node);
});

return css => {
fetchAllImports(css);
linkImportedSymbols(css);
extractExports(css);
}
});
7 changes: 7 additions & 0 deletions test/cssi/interchange-format/colors.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
:export {
blackShadow: x__single_import_export_colors__blackShadow;
}

.x__single_import_export_colors__blackShadow {
box-shadow: 0 0 10px -2px black;
}
6 changes: 6 additions & 0 deletions test/cssi/interchange-format/expected.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.x__single_import_export_colors__blackShadow {
box-shadow: 0 0 10px -2px black;
}
.x__single_import_export_source__localName {
color: red;
}
3 changes: 3 additions & 0 deletions test/cssi/interchange-format/expected.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"localName": "x__single_import_export_source__localName x__single_import_export_colors__blackShadow"
}
11 changes: 11 additions & 0 deletions test/cssi/interchange-format/source.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
:import("./colors.css") {
i__tmp_import_djhgdsag: blackShadow;
}

:export {
localName: x__single_import_export_source__localName i__tmp_import_djhgdsag;
}

.x__single_import_export_source__localName {
color: red;
}
4 changes: 4 additions & 0 deletions test/cssi/pseudo-variables/colors.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
:export {
black: #222;
white: #ddd;
}
5 changes: 5 additions & 0 deletions test/cssi/pseudo-variables/expected.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

.x__lol {
color: #222;
background: #ddd;
}
3 changes: 3 additions & 0 deletions test/cssi/pseudo-variables/expected.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"lol": "x__lol"
}
13 changes: 13 additions & 0 deletions test/cssi/pseudo-variables/source.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
:import("./colors.css") {
i__black: black;
i__white: white;
}

:export {
lol: x__lol;
}

.x__lol {
color: i__black;
background: i__white;
}
4 changes: 0 additions & 4 deletions test/example.css

This file was deleted.

31 changes: 0 additions & 31 deletions test/index.js

This file was deleted.

Loading