-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathindex.js
More file actions
306 lines (257 loc) · 11.5 KB
/
index.js
File metadata and controls
306 lines (257 loc) · 11.5 KB
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import { resolve, dirname, isAbsolute } from 'path';
// options resolvers
import * as requireHooksOptions from './options_resolvers';
// utils.
import { extractCssFile } from './utils';
const defaultOptions = {
generateScopedName: '[name]__[local]___[hash:base64:5]'
};
function updateStyleSheetPath(pathStringLiteral, importPathFormatter) {
if (!importPathFormatter) { return pathStringLiteral; }
return {
...pathStringLiteral,
value: importPathFormatter(pathStringLiteral.value)
};
}
function findExpressionStatementChild(path, t) {
const parent = path.parentPath;
if (!parent) {
throw new Error('Invalid expression structure');
}
if (
t.isExpressionStatement(parent)
|| t.isProgram(parent)
|| t.isBlockStatement(parent)
) {
return path;
}
return findExpressionStatementChild(parent, t);
}
export default function transformCssModules({ types: t }) {
function resolveModulePath(filename) {
const dir = dirname(filename);
if (isAbsolute(dir)) return dir;
if (process.env.PWD) return resolve(process.env.PWD, dir);
return resolve(dir);
}
/**
*
* @param {String} filepath javascript file path
* @param {String} cssFile requireed css file path
* @returns {Array} array of class names
*/
function requireCssFile(filepath, cssFile) {
let filePathOrModuleName = cssFile;
// only resolve path to file when we have a file path
if (!/^\w/i.test(filePathOrModuleName)) {
const from = resolveModulePath(filepath);
filePathOrModuleName = resolve(from, filePathOrModuleName);
}
// css-modules-require-hooks throws if file is ignored
try {
return require(filePathOrModuleName);
} catch (e) {
// As a last resort, require the cssFile itself. This enables loading of CSS files from external deps
try {
return require(cssFile);
} catch (f) {
return {}; // return empty object, this simulates result of ignored stylesheet file
}
}
}
// is css modules require hook initialized?
let initialized = false;
// are we requiring a module for preprocessCss, processCss, etc?
// we don't want them to be transformed using this plugin
// because it will cause circular dependency in babel-node and babel-register process
let inProcessingFunction = false;
let matchExtensions = /\.css$/i;
function matcher(extensions = ['.css']) {
const extensionsPattern = extensions.join('|').replace(/\./g, '\\\.');
return new RegExp(`(${extensionsPattern})$`, 'i');
}
function buildClassNameToScopeNameMap(tokens) {
/* eslint-disable new-cap */
return t.ObjectExpression(
Object.keys(tokens).map(token =>
t.ObjectProperty(
t.StringLiteral(token),
t.StringLiteral(tokens[token])
)
)
);
}
const cssMap = new Map();
let thisPluginOptions = null;
const pluginApi = {
manipulateOptions(options) {
if (initialized || inProcessingFunction) {
return options;
}
// find options for this plugin
// we have to use this hack because plugin.key does not have to be 'css-modules-transform'
// so we will identify it by comparing manipulateOptions
if (Array.isArray(options.plugins[0])) { // babel 6
thisPluginOptions = options.plugins.filter(
([plugin]) => plugin.manipulateOptions === pluginApi.manipulateOptions
)[0][1];
} else { // babel 7
thisPluginOptions = options.plugins.filter(
(plugin) => plugin.manipulateOptions === pluginApi.manipulateOptions
)[0].options;
}
const currentConfig = { ...defaultOptions, ...thisPluginOptions };
// this is not a css-require-ook config
delete currentConfig.extractCss;
delete currentConfig.keepImport;
delete currentConfig.importPathFormatter;
// match file extensions, speeds up transform by creating one
// RegExp ahead of execution time
matchExtensions = matcher(currentConfig.extensions);
const pushStylesCreator = (toWrap) => (css, filepath) => {
let processed;
if (typeof toWrap === 'function') {
processed = toWrap(css, filepath);
}
if (typeof processed !== 'string') processed = css;
// set css content only if is new
if (!cssMap.has(filepath) || cssMap.get(filepath) !== processed) {
cssMap.set(filepath, processed);
}
return processed;
};
// resolve options
Object.keys(requireHooksOptions).forEach(key => {
// skip undefined options
if (currentConfig[key] === undefined) {
if (key === 'importPathFormatter' && thisPluginOptions && thisPluginOptions[key]) {
thisPluginOptions[key] = requireHooksOptions[key](thisPluginOptions[key]);
}
return;
}
inProcessingFunction = true;
currentConfig[key] = requireHooksOptions[key](currentConfig[key], currentConfig);
inProcessingFunction = false;
});
// wrap or define processCss function that collect generated css
currentConfig.processCss = pushStylesCreator(currentConfig.processCss);
require('css-modules-require-hook')(currentConfig);
initialized = true;
return options;
},
post() {
// extract css only if is this option set
if (thisPluginOptions && thisPluginOptions.extractCss) {
// always rewrite file :-/
extractCssFile(
process.cwd(),
cssMap,
thisPluginOptions.extractCss
);
}
},
visitor: {
// import styles from './style.css';
ImportDefaultSpecifier(path, { file }) {
const { value } = path.parentPath.node.source;
if (matchExtensions.test(value)) {
const requiringFile = file.opts.filename;
const tokens = requireCssFile(requiringFile, value);
const varDeclaration = t.variableDeclaration(
'var',
[
t.variableDeclarator(
t.identifier(path.node.local.name),
buildClassNameToScopeNameMap(tokens)
)
]
);
if (thisPluginOptions && thisPluginOptions.keepImport === true) {
path.parentPath.replaceWithMultiple([
t.expressionStatement(
t.callExpression(
t.identifier('require'),
[updateStyleSheetPath(t.stringLiteral(value), thisPluginOptions.importPathFormatter)]
)
),
varDeclaration
]);
} else {
path.parentPath.replaceWith(varDeclaration);
}
}
},
ImportDeclaration(path, { file }) {
const { value } = path.node.source;
if (matchExtensions.test(value)) {
const requiringFile = file.opts.filename;
const tokens = requireCssFile(requiringFile, value);
const memberImports = path.node.specifiers.filter(specifier => {
return specifier.type === 'ImportSpecifier';
});
if (memberImports.length > 0) {
const transforms = [];
memberImports.forEach(memberImport => {
const memberName = memberImport.imported.name;
const memberValue = tokens[memberName] || '';
const varDeclaration = t.variableDeclaration(
'var',
[
t.variableDeclarator(
t.identifier(memberName),
t.stringLiteral(memberValue)
)
]
);
transforms.push(varDeclaration);
});
if (thisPluginOptions && thisPluginOptions.keepImport === true) {
path.replaceWithMultiple([
t.expressionStatement(
t.callExpression(
t.identifier('require'),
[updateStyleSheetPath(t.stringLiteral(value), thisPluginOptions.importPathFormatter)]
)
),
...transforms
]);
} else {
path.replaceWithMultiple(transforms);
}
}
}
},
// const styles = require('./styles.css');
CallExpression(path, { file }) {
const { callee: { name: calleeName }, arguments: args } = path.node;
if (calleeName !== 'require' || !args.length || !t.isStringLiteral(args[0])) {
return;
}
const [{ value: stylesheetPath }] = args;
if (matchExtensions.test(stylesheetPath)) {
const requiringFile = file.opts.filename;
const tokens = requireCssFile(requiringFile, stylesheetPath);
// if parent expression is not a Program, replace expression with tokens
// Otherwise remove require from file, we just want to get generated css for our output
if (!t.isExpressionStatement(path.parent)) {
path.replaceWith(buildClassNameToScopeNameMap(tokens));
// Keeped import will places before closest expression statement child
if (thisPluginOptions && thisPluginOptions.keepImport === true) {
findExpressionStatementChild(path, t).insertBefore(
t.expressionStatement(
t.callExpression(
t.identifier('require'),
[updateStyleSheetPath(t.stringLiteral(stylesheetPath), thisPluginOptions.importPathFormatter)]
)
)
);
}
} else if (!thisPluginOptions || thisPluginOptions.keepImport !== true) {
path.remove();
}
}
}
}
};
return pluginApi;
}