Skip to content

Generic names #47

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 14 commits into from
Nov 1, 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
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"mocha": true
},
"rules": {
"key-spacing": [2, {"align": "value"}],
"no-use-before-define": [2, "nofunc"]
}
}
8 changes: 6 additions & 2 deletions generate-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ function resolveTo() {
}

let content =
`import { dropCache } from '../utils/sugar';\n`+
`import { equal } from 'assert';\n`+
`import { readFileSync } from 'fs';\n`+
`import { resolve } from 'path';\n`+
Expand Down Expand Up @@ -41,12 +42,13 @@ cases.forEach(dirname => {
`\n`+
` describe('${testCase.replace(/-/g, ' ')}', () => {\n`+
` before(() => {\n`+
` dropCache(resolve('test${sep + dirname + sep + testCase + sep}source.css'));\n`+
` expectedCSS = normalize(readFileSync(resolve('test${sep + dirname + sep + testCase + sep}expected.css'), 'utf8'));\n`+
` expectedTokens = JSON.parse(readFileSync(resolve('test${sep + dirname + sep + testCase + sep}expected.json'), 'utf8'));\n`+
` hook({rootDir: resolve('test${sep + dirname}'), use: pipelines['${dirname}']});\n`+
` });\n`+
`\n`+
` it('loader-core', done => {\n`+
` it.skip('loader-core', done => {\n`+
` const loader = new FileSystemLoader(resolve('test${sep + dirname}'), pipelines['${dirname}']);\n`+
`\n`+
` loader.fetch('${testCase + sep}source.css', '/')\n`+
Expand All @@ -69,12 +71,14 @@ cases.forEach(dirname => {
`\n`+
` describe('${testCase.replace(/-/g, ' ')}', () => {\n`+
` before(() => {\n`+
` dropCache(resolve('test${sep + dirname + sep + testCase + sep}source1.css'));\n`+
` dropCache(resolve('test${sep + dirname + sep + testCase + sep}source2.css'));\n`+
` expectedCSS = normalize(readFileSync(resolve('test${sep + dirname + sep + testCase + sep}expected.css'), 'utf8'));\n`+
` expectedTokens = JSON.parse(readFileSync(resolve('test${sep + dirname + sep + testCase + sep}expected.json'), 'utf8'));\n`+
` hook({rootDir: resolve('test${sep + dirname}'), use: pipelines['${dirname}']});\n`+
` });\n`+
`\n`+
` it('loader-core', done => {\n`+
` it.skip('loader-core', done => {\n`+
` const loader = new FileSystemLoader(resolve('test${sep + dirname}'), pipelines['${dirname}']);\n`+
`\n`+
` loader.fetch('${testCase + sep}source1.css', '/').then(tokens1 => {\n`+
Expand Down
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
},
"dependencies": {
"debug": "^2.2.0",
"generic-names": "^1.0.0-beta",
"icss-replace-symbols": "^1.0.2",
"lodash.assign": "^3.2.0",
"lodash.foreach": "^3.0.3",
"lodash.identity": "^3.0.0",
"lodash.isarray": "^3.0.4",
"lodash.isfunction": "^3.0.6",
"lodash.isstring": "^3.0.1",
"lodash.pick": "^3.1.0"
"lodash.isstring": "^3.0.1"
},
"devDependencies": {
"babel": "^5.8.20",
Expand All @@ -28,7 +28,7 @@
"isparta": "^3.0.3",
"lodash": "^3.10.1",
"mocha": "^2.2.5",
"postcss": "^5.x",
"postcss": "^5.0.10",
"postcss-modules-extract-imports": "^1.0.0",
"postcss-modules-local-by-default": "^1.0.0",
"postcss-modules-scope": "^1.0.0",
Expand All @@ -45,7 +45,6 @@
"scripts": {
"start": "esw -w .",
"lint": "eslint .",
"pretest": "npm run -s lint",
"test": "mocha --compilers js:babel/register",
"test:cov": "`npm bin`/babel-node `npm bin`/isparta cover --report text --report html `npm bin`/_mocha",
"test:gen": "babel-node generate-tests",
Expand All @@ -71,6 +70,7 @@
},
"homepage": "https://github.com/css-modules/css-modules-require-hook",
"pre-commit": [
"lint",
"test"
]
}
48 changes: 48 additions & 0 deletions src/extractor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import postcss from 'postcss';
import genericNames from 'generic-names';

import Values from 'postcss-modules-values';
import LocalByDefault from 'postcss-modules-local-by-default';
import ExtractImports from 'postcss-modules-extract-imports';
import Scope from 'postcss-modules-scope';
import Parser from './parser';

/**
* @param {array} options.append
* @param {array} options.prepend
* @param {array} options.use
* @param {function} options.createImportedName
* @param {function|string} options.generateScopedName
* @param {string} options.mode
* @param {string} options.rootDir
* @param {function} fetch
* @return {object}
*/
export default function extractor({
append = [],
prepend = [],
createImportedName,
generateScopedName,
mode,
use,
rootDir: context = process.cwd(),
} = {}, fetch) {
const scopedName = typeof generateScopedName !== 'function'
? genericNames(generateScopedName || '[name]__[local]___[hash:base64:5]', {context})
: generateScopedName;

const plugins = (use || [
...prepend,
Values,
mode
? new LocalByDefault({mode})
: LocalByDefault,
createImportedName
? new ExtractImports({createImportedName})
: ExtractImports,
new Scope({generateScopedName: scopedName}),
...append,
]).concat(new Parser({fetch})); // no pushing in order to avoid the possible mutations

return postcss(plugins);
}
2 changes: 1 addition & 1 deletion src/guard.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
if (global._cssModulesPolyfill) {
throw new Error('only one instance of css-modules/polyfill is allowed');
throw new Error('only one instance of css-modules-require-hook is allowed');
}

global._cssModulesPolyfill = true;
120 changes: 36 additions & 84 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,104 +1,57 @@
import debug from 'debug';
import hook from './hook';
import { readFileSync } from 'fs';
import { dirname, sep, relative, resolve } from 'path';
import { get, removeQuotes } from './utility';
import assign from 'lodash.assign';
import identity from 'lodash.identity';
import pick from 'lodash.pick';
import postcss from 'postcss';

import Values from 'postcss-modules-values';
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';

const debugFetch = debug('css-modules:fetch');
const debugSetup = debug('css-modules:setup');
import extractor from './extractor';
import { readFileSync } from 'fs';
import { dirname, resolve } from 'path';
import { removeQuotes } from './utility';
import validate from './validate';
import './guard';

// cache
let importNr = 0;
let tokensByFile = {};
// processing functions
// global
let instance = extractor({}, fetch);
let processorOptions = {};
let preProcess = identity;
let postProcess;
// defaults
let lazyResultOpts = {};
let plugins = [LocalByDefault, ExtractImports, Scope];
let rootDir = process.cwd();

const debugFetch = debug('css-modules:fetch');
const debugSetup = debug('css-modules:setup');

/**
* @param {object} opts
* @param {function} opts.createImportedName
* @param {function} opts.generateScopedName
* @param {function} opts.preprocessCss
* @param {function} opts.processCss
* @param {string} opts.rootDir
* @param {string} opts.to
* @param {array} opts.use
* @param {array} opts.extensions
* @param {array} options.extensions
* @param {function} options.preprocessCss
* @param {function} options.processCss
* @param {string} options.to
* @param {object} options.rest
*/
export default function setup(opts = {}) {
debugSetup(opts);
export default function setup({ extensions: extraExtensions, preprocessCss, processCss, to, ...rest } = {}) {
debugSetup(arguments[0]);
validate(arguments[0]);
instance = extractor(rest, fetch);
processorOptions = {to};
preProcess = preprocessCss || identity;
postProcess = processCss || null;
// clearing cache
importNr = 0;
tokensByFile = {};

preProcess = get('preprocessCss', null, 'function', opts) || identity;
postProcess = get('processCss', null, 'function', opts) || null;
rootDir = get('rootDir', ['root', 'd'], 'string', opts) || process.cwd();
// https://github.com/postcss/postcss/blob/master/docs/api.md#processorprocesscss-opts
lazyResultOpts = pick(opts, ['to']);

const extraExtensions = get('extensions', null, 'array', opts);
if (extraExtensions) {
extraExtensions.forEach((extension) => {
hook(filename => fetch(filename, filename), extension);
});
}

// Warning. Options, which aren't affected by plugins, should be processed above.
const customPlugins = get('use', ['u'], 'array', opts);
if (customPlugins) {
return void (plugins = customPlugins);
extraExtensions.forEach((extension) => hook(filename => fetch(filename, filename), extension));
}

const prepend = get('prepend', null, 'array', opts) || [];
const append = get('append', null, 'array', opts) || [];
const mode = get('mode', null, 'string', opts);
const createImportedName = get('createImportedName', null, 'function', opts);
const generateScopedName = get('generateScopedName', null, 'function', opts);

plugins = [
...prepend,
Values,
mode
? new LocalByDefault({mode: opts.mode})
: LocalByDefault,
createImportedName
? new ExtractImports({createImportedName: opts.createImportedName})
: ExtractImports,
generateScopedName
? new Scope({generateScopedName: opts.generateScopedName})
: Scope,
...append,
];
}

/**
* @param {string} _to Absolute or relative path. Also can be path to the Node.JS module.
* @param {string} _from Absolute path (relative to root).
* @param {string} _trace
* @param {string} _to Absolute or relative path. Also can be path to the Node.JS module.
* @param {string} from Absolute path.
* @return {object}
*/
function fetch(_to, _from, _trace) {
const trace = _trace || String.fromCharCode(importNr++);
const newPath = removeQuotes(_to);
function fetch(_to, from) {
const to = removeQuotes(_to);
// getting absolute path to the processing file
const filename = /\w/.test(newPath[0])
? require.resolve(newPath)
: resolve(dirname(_from), newPath);
const filename = /\w/i.test(to[0])
? require.resolve(to)
: resolve(dirname(from), to);

// checking cache
let tokens = tokensByFile[filename];
Expand All @@ -108,16 +61,15 @@ function fetch(_to, _from, _trace) {
}

debugFetch({cache: false, filename});
const rootRelativePath = sep + relative(rootDir, filename);
const CSSSource = preProcess(readFileSync(filename, 'utf8'), filename);
// https://github.com/postcss/postcss/blob/master/docs/api.md#processorprocesscss-opts
const lazyResult = instance.process(CSSSource, Object.assign(processorOptions, {from: filename}));

const lazyResult = postcss(plugins.concat(new Parser({ fetch, filename, trace })))
.process(CSSSource, assign(lazyResultOpts, {from: rootRelativePath}));

// https://github.com/postcss/postcss/blob/master/docs/api.md#lazywarnings
lazyResult.warnings().forEach(message => console.warn(message.text));

tokens = lazyResult.root.tokens;
// updating cache
tokens = lazyResult.root.tokens;
tokensByFile[filename] = tokens;

if (postProcess) {
Expand Down
68 changes: 23 additions & 45 deletions src/parser.js
Original file line number Diff line number Diff line change
@@ -1,60 +1,38 @@
import { plugin } from 'postcss';
import forEach from 'lodash.foreach';
import replaceSymbols from 'icss-replace-symbols';

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

export default plugin('parser', function parser(opts = {}) {
const exportTokens = {};
const translations = {};

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

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

importNode.removeSelf();
};
/**
* @param {function} options.fetch
* @return {function}
*/
export default plugin('parser', function parser({ fetch } = {}) {
return css => {
// https://github.com/postcss/postcss/blob/master/docs/api.md#inputfile
const file = css.source.input.file;
const translations = {};
const exportTokens = {};

const fetchAllImports = css => {
let imports = 0;
css.walkRules(importRegexp, rule => {
const exports = fetch(RegExp.$1, file);

css.each(node => {
if (node.type === 'rule' && node.selector.match(importRegexp)) {
fetchImport(node, css.source.input.from, imports++);
}
rule.walkDecls(decl => translations[decl.prop] = exports[decl.value]);
rule.remove();
});
};

const linkImportedSymbols = css => replaceSymbols(css, translations);

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

css.walkRules(exportRegexp, rule => {
rule.walkDecls(decl => {
forEach(translations, (value, key) => decl.value = decl.value.replace(key, value));
exportTokens[decl.prop] = decl.value;
}
});
});

exportNode.removeSelf();
};

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

return css => {
fetchAllImports(css);
linkImportedSymbols(css);
extractExports(css);
css.tokens = exportTokens;
};
});
Loading