-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
231 lines (192 loc) · 7.33 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
219
220
221
222
223
224
225
226
227
228
229
230
231
'use strict';
const fs = require('fs');
const path = require('path');
const Promise = require('rsvp').Promise;
const Writer = require('broccoli-caching-writer');
const mkdirp = require('mkdirp');
const symlinkOrCopy = require('symlink-or-copy');
const ensurePosixPath = require('ensure-posix-path');
const postcss = require('postcss');
const linkModules = require('./lib/link-modules');
const values = require('postcss-modules-values');
const localByDefault = require('postcss-modules-local-by-default');
const extractImports = require('postcss-modules-extract-imports');
const scope = require('postcss-modules-scope');
module.exports = class CSSModules extends Writer {
constructor(inputNode, _options) {
let options = _options || {};
let extension = options.extension || 'css';
super([inputNode], Object.assign({
cacheInclude: [new RegExp(`\\.${extension}$`)]
}, options));
this.plugins = unwrapPlugins(options.plugins || []);
this.encoding = options.encoding || 'utf-8';
this.extension = extension;
this.generateScopedName = options.generateScopedName || scope.generateScopedName;
this.resolvePath = options.resolvePath || resolvePath;
this.onProcessFile = options.onProcessFile;
this.formatJS = options.formatJS;
this.formatCSS = options.formatCSS;
this.enableSourceMaps = options.enableSourceMaps;
this.sourceMapBaseDir = options.sourceMapBaseDir;
this.postcssOptions = options.postcssOptions || {};
this.virtualModules = options.virtualModules || Object.create(null);
this.onModuleResolutionFailure = options.onModuleResolutionFailure || function(failure) { throw failure; };
this.onImportResolutionFailure = options.onImportResolutionFailure;
this.getJSFilePath = options.getJSFilePath || this.getJSFilePath;
this.onBuildStart = options.onBuildStart || (() => {});
this.onBuildEnd = options.onBuildEnd || (() => {});
this.onBuildSuccess = options.onBuildSuccess || (() => {});
this.onBuildError = options.onBuildError || (() => {});
this._seen = null;
}
build() {
this._seen = Object.create(null);
this.onBuildStart();
// TODO this could cache much more than it currently does across rebuilds, but we'd need to be smart to invalidate
// things correctly when dependencies change
let processPromises = this.listFiles().map((sourcePath) => {
return this.process(ensurePosixPath(sourcePath));
});
return Promise.all(processPromises)
.then((result) => {
this.onBuildSuccess();
this.onBuildEnd();
return result;
})
.catch((error) => {
this.onBuildError();
this.onBuildEnd();
throw error;
});
}
process(sourcePath) {
let relativeSource = sourcePath.substring(this.inputPaths[0].length + 1);
let cssDestinationPath = this.outputPath + '/' + relativeSource;
// If the file isn't an extension we care about, just copy it over untouched
if (sourcePath.lastIndexOf('.' + this.extension) !== sourcePath.length - this.extension.length - 1) {
mkdirp.sync(path.dirname(cssDestinationPath));
symlinkOrCopy.sync(sourcePath, cssDestinationPath);
return;
}
if (this.onProcessFile) {
this.onProcessFile(sourcePath);
}
return this.loadPath(sourcePath).then(function(result) {
let jsDestinationPath = this.outputPath + '/' + this.getJSFilePath(relativeSource);
let css = this.formatInjectableSource(result.injectableSource, relativeSource);
let js = this.formatExportTokens(result.exportTokens, relativeSource);
mkdirp.sync(path.dirname(cssDestinationPath));
fs.writeFileSync(cssDestinationPath, css, this.encoding);
mkdirp.sync(path.dirname(jsDestinationPath));
fs.writeFileSync(jsDestinationPath, js, this.encoding);
}.bind(this));
}
getJSFilePath(cssPath) {
return cssPath.replace(new RegExp(`\\.${this.extension}$`), '.js');
}
posixInputPath() {
return ensurePosixPath(this.inputPaths[0]);
}
formatExportTokens(exportTokens, modulePath) {
if (this.formatJS) {
return this.formatJS(exportTokens, modulePath);
} else {
return 'export default ' + JSON.stringify(exportTokens, null, 2) + ';';
}
}
formatInjectableSource(injectableSource, modulePath) {
if (this.formatCSS) {
return this.formatCSS(injectableSource, modulePath);
} else if (this.enableSourceMaps) {
return injectableSource;
} else {
return '/* styles for ' + modulePath + ' */\n' + injectableSource;
}
}
// Hook for css-module-loader-core to fetch the exported tokens for a given import
fetchExports(importPath, fromFile) {
let relativePath = ensurePosixPath(importPath);
if (relativePath in this.virtualModules) {
return Promise.resolve(this.virtualModules[relativePath]);
}
let absolutePath = this.resolvePath(relativePath, ensurePosixPath(fromFile));
return this.loadPath(absolutePath).then(function(result) {
return result.exportTokens;
});
}
loadPath(dependency) {
let seen = this._seen;
let absolutePath = dependency.toString();
let loadPromise = seen[absolutePath];
if (!loadPromise) {
loadPromise = new Promise(function(resolve) {
let content = fs.readFileSync(absolutePath, this.encoding);
resolve(this.load(content, dependency));
}.bind(this));
seen[absolutePath] = loadPromise;
}
return loadPromise;
}
generateRelativeScopedName(dependency, className, absolutePath, fullRule) {
let relativePath = ensurePosixPath(absolutePath).replace(this.posixInputPath() + '/', '');
return this.generateScopedName(className, relativePath, fullRule, dependency);
}
load(content, dependency) {
let options = this.processorOptions({
from: dependency.toString(),
relativeFrom: dependency.toString().substring(this.inputPaths[0].length + 1),
map: this.sourceMapOptions()
});
let processor = postcss([]
.concat(this.plugins.before)
.concat(this.loaderPlugins(dependency))
.concat(this.plugins.after));
return processor.process(content, options).then(function(result) {
return { injectableSource: result.css, exportTokens: result.exportTokens };
});
}
processorOptions(additional) {
return Object.assign({}, additional, this.postcssOptions);
}
sourceMapOptions() {
if (!this.enableSourceMaps) return;
let dir = this.sourceMapBaseDir ? ('/' + ensurePosixPath(this.sourceMapBaseDir)) : '';
return {
inline: true,
sourcesContent: true,
annotation: this.posixInputPath() + dir + '/output.map'
};
}
loaderPlugins(dependency) {
return [
values,
localByDefault,
extractImports,
scope({
generateScopedName: this.generateRelativeScopedName.bind(this, dependency)
}),
linkModules({
fetchExports: this.fetchExports.bind(this),
onModuleResolutionFailure: this.onModuleResolutionFailure,
onImportResolutionFailure: this.onImportResolutionFailure
})
];
}
};
function resolvePath(relativePath, fromFile) {
return ensurePosixPath(path.resolve(path.dirname(fromFile), relativePath));
}
function unwrapPlugins(plugins) {
if (Array.isArray(plugins)) {
return {
before: [],
after: plugins
};
} else {
return {
before: plugins.before || [],
after: plugins.after || []
};
}
}