-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathindex.js
218 lines (175 loc) · 5.84 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Some css-modules-loader-code dependencies use Promise so we'll provide it for older node versions
if (!global.Promise) { global.Promise = require('promise-polyfill') }
var fs = require('fs');
var path = require('path');
var through = require('through');
var extractor = require('./extractor');
var FileSystemLoader = require('css-modules-loader-core/lib/file-system-loader');
var assign = require('object-assign');
var stringHash = require('string-hash');
var ReadableStream = require('stream').Readable;
/*
Custom `generateScopedName` function for `postcss-modules-scope`.
Short names consisting of source hash and line number.
*/
function generateShortName (name, filename, css, context) {
filename = path.relative(context, filename);
// first occurrence of the name
// TOOD: better match with regex
var i = css.indexOf('.' + name);
var numLines = css.substr(0, i).split(/[\r\n]/).length;
var hash = stringHash(css).toString(36).substr(0, 5);
return '_' + name + '_' + hash + '_' + numLines;
}
/*
Custom `generateScopedName` function for `postcss-modules-scope`.
Appends a hash of the css source.
*/
function generateLongName (name, filename, css, context) {
filename = path.relative(context, filename);
var sanitisedPath = filename.replace(/\.[^\.\/\\]+$/, '')
.replace(/[\W_]+/g, '_')
.replace(/^_|_$/g, '');
return '_' + sanitisedPath + '__' + name;
}
/*
Get the default plugins and apply options.
*/
function getDefaultPlugins (options) {
var scope = Core.scope;
var customNameFunc = options.generateScopedName;
var defaultNameFunc = process.env.NODE_ENV === 'production' ?
generateShortName :
generateLongName;
scope.generateScopedName = customNameFunc || defaultNameFunc;
return [
Core.values
, Core.localByDefault
, Core.extractImports
, scope
];
}
/*
Normalize the manifest paths so that they are always relative
to the project root directory.
*/
function normalizeManifestPaths (tokensByFile, rootDir) {
var output = {};
var rootDirLength = rootDir.length + 1;
Object.keys(tokensByFile).forEach(function (filename) {
var normalizedFilename = filename.substr(rootDirLength);
output[normalizedFilename] = tokensByFile[filename];
});
return output;
}
var cssExt = /\.css$/;
// caches
//
// persist these for as long as the process is running. #32
// keep track of css files visited
var filenames = [];
// keep track of all tokens so we can avoid duplicates
var tokensByFile = {};
// keep track of all source files for later builds: when
// using watchify, not all files will be caught on subsequent
// bundles
var sourceByFile = {};
module.exports = function (browserify, options) {
options = options || {};
options.rootDir = options.rootDir || options.d || undefined;
options.append = options.postcssAfter || options.after || [];
options.use = options.use || options.u || undefined;
var cssOutFilename = options.output || options.o;
var jsonOutFilename = options.json || options.jsonOutput;
// the compiled CSS stream needs to be avalible to the transform,
// but re-created on each bundle call.
var compiledCssStream;
var instance = extractor(options, fetch);
function fetch(_to, from) {
var to = _to.replace(/^["']|["']$/g, '');
return new Promise(function (resolve, reject) {
try {
var filename = /\w/i.test(to[0])
? require.resolve(to)
: path.resolve(path.dirname(from), to);
} catch (e) {
return void reject(e);
}
fs.readFile(filename, 'utf8', function (err, css) {
if (err) {
return void reject(err);
}
instance.process(css, {from: filename})
.then(function (result) {
var css = result.css;
var tokens = result.root.tokens;
assign(tokensByFile, tokens);
sourceByFile[filename] = css;
compiledCssStream.push(css);
resolve(tokens);
})
.catch(reject);
});
});
}
function transform (filename) {
// only handle .css files
if (!cssExt.test(filename)) {
return through();
}
// collect visited filenames
filenames.push(filename);
return through(function noop () {}, function end () {
var self = this;
fetch(filename, filename)
.then(function (tokens) {
var output = 'module.exports = ' + JSON.stringify(tokens);
self.queue(output);
self.queue(null);
})
.catch(function (err) {
self.emit('error', err);
});
});
}
browserify.transform(transform, {
global: true
});
browserify.on('bundle', function (bundle) {
// on each bundle, create a new stream b/c the old one might have ended
compiledCssStream = new ReadableStream();
compiledCssStream._read = function () {};
bundle.emit('css stream', compiledCssStream);
bundle.on('end', function () {
// Combine the collected sources into a single CSS file
var files = Object.keys(sourceByFile);
var css;
// end the output stream
compiledCssStream.push(null);
// write the css file
if (cssOutFilename) {
css = files.map(function (file) {
return sourceByFile[file];
}).join('\n');
fs.writeFile(cssOutFilename, css, function (err) {
if (err) {
browserify.emit('error', err);
}
});
}
// write the classname manifest
if (jsonOutFilename) {
fs.writeFile(jsonOutFilename, JSON.stringify(normalizeManifestPaths(tokensByFile, rootDir)), function (err) {
if (err) {
browserify.emit('error', err);
}
});
}
// reset the `tokensByFile` cache
tokensByFile = {};
});
});
return browserify;
};
module.exports.generateShortName = generateShortName;
module.exports.generateLongName = generateLongName;