Skip to content

Generic names #46

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 6 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
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
},
"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",
Expand All @@ -28,7 +30,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 Down
49 changes: 49 additions & 0 deletions src/extractor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
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 function get({
append = [],
prepend = [],
createImportedName,
generateScopedName,
mode,
use,
rootDir: context = process.cwd(),
} = {}, fetch) {
if (typeof generateScopedName !== 'function') {
generateScopedName = genericNames(generateScopedName || '[name]__[local]___[hash:base64:5]', {context});
}

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

plugins.push(new Parser({fetch}));
return postcss(plugins);
}
120 changes: 34 additions & 86 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,104 +1,52 @@
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 { get } from './extractor';
import { readFileSync } from 'fs';
import { dirname, resolve } from 'path';
import { removeQuotes } from './utility';

// cache
let importNr = 0;
let tokensByFile = {};
// processing functions
// global
let extractorOptions;
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);
// clearing cache
importNr = 0;
tokensByFile = {};
export default function setup({ extensions: extraExtensions, preprocessCss, processCss, to, ...rest } = {}) {
debugSetup(arguments[0]);
extractorOptions = rest;
processorOptions = {to};
preProcess = preprocessCss || identity;
postProcess = processCss || null;

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 +56,16 @@ 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 = get(extractorOptions, fetch)
.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;
};
});
8 changes: 8 additions & 0 deletions src/utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ const check = {
*/
export function get(prop, aliases, type, source) {
if (source[prop]) {
if (isArray(type)) {
if (type.some(tp => is(tp, source[prop]))) {
return source[prop];
}

throw new Error(format('should specify %s for %s', type.join('|'), prop));
}

if (!is(type, source[prop])) {
throw new Error(format('should specify %s for %s', type, prop));
}
Expand Down