-
-
Notifications
You must be signed in to change notification settings - Fork 163
/
index.js
271 lines (223 loc) · 8.12 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
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
// @flow
import {
dirname,
resolve
} from 'path';
import babelPluginJsxSyntax from '@babel/plugin-syntax-jsx';
import BabelTypes from '@babel/types';
import ajvKeywords from 'ajv-keywords';
import Ajv from 'ajv';
import optionsSchema from './schemas/optionsSchema.json';
import optionsDefaults from './schemas/optionsDefaults';
import createObjectExpression from './createObjectExpression';
import requireCssModule from './requireCssModule';
import resolveStringLiteral from './resolveStringLiteral';
import replaceJsxExpressionContainer from './replaceJsxExpressionContainer';
import attributeNameExists from './attributeNameExists';
const ajv = new Ajv({
// eslint-disable-next-line id-match
$data: true
});
ajvKeywords(ajv);
const validate = ajv.compile(optionsSchema);
export default ({
types: t
}: {
types: BabelTypes
}) => {
const filenameMap = {};
let skip = false;
const setupFileForRuntimeResolution = (path, filename) => {
const programPath = path.findParent((parentPath) => {
return parentPath.isProgram();
});
filenameMap[filename].importedHelperIndentifier = programPath.scope.generateUidIdentifier('getClassName');
filenameMap[filename].styleModuleImportMapIdentifier = programPath.scope.generateUidIdentifier('styleModuleImportMap');
programPath.unshiftContainer(
'body',
t.importDeclaration(
[
t.importDefaultSpecifier(
filenameMap[filename].importedHelperIndentifier
)
],
t.stringLiteral('babel-plugin-react-css-modules/dist/browser/getClassName')
)
);
const firstNonImportDeclarationNode = programPath.get('body').find((node) => {
return !t.isImportDeclaration(node);
});
firstNonImportDeclarationNode.insertBefore(
t.variableDeclaration(
'const',
[
t.variableDeclarator(
filenameMap[filename].styleModuleImportMapIdentifier,
createObjectExpression(t, filenameMap[filename].styleModuleImportMap)
)
]
)
);
// eslint-disable-next-line no-console
// console.log('setting up', filename, util.inspect(filenameMap,{depth: 5}))
};
const addWebpackHotModuleAccept = (path) => {
const test = t.memberExpression(t.identifier('module'), t.identifier('hot'));
const consequent = t.blockStatement([
t.expressionStatement(
t.callExpression(
t.memberExpression(
t.memberExpression(t.identifier('module'), t.identifier('hot')),
t.identifier('accept')
),
[
t.stringLiteral(path.node.source.value),
t.functionExpression(null, [], t.blockStatement([
t.expressionStatement(
t.callExpression(
t.identifier('require'),
[t.stringLiteral(path.node.source.value)]
)
)
]))
]
)
)
]);
const programPath = path.findParent((parentPath) => {
return parentPath.isProgram();
});
const firstNonImportDeclarationNode = programPath.get('body').find((node) => {
return !t.isImportDeclaration(node);
});
const hotAcceptStatement = t.ifStatement(test, consequent);
if (firstNonImportDeclarationNode) {
firstNonImportDeclarationNode.insertBefore(hotAcceptStatement);
} else {
programPath.pushContainer('body', hotAcceptStatement);
}
};
const getTargetResourcePath = (path: *, stats: *) => {
const targetFileDirectoryPath = dirname(stats.file.opts.filename);
if (path.node.source.value.startsWith('.')) {
return resolve(targetFileDirectoryPath, path.node.source.value);
}
return require.resolve(path.node.source.value);
};
const isFilenameExcluded = (filename, exclude) => {
return filename.match(new RegExp(exclude));
};
const notForPlugin = (path: *, stats: *) => {
stats.opts.filetypes = stats.opts.filetypes || {};
const extension = path.node.source.value.lastIndexOf('.') > -1 ? path.node.source.value.substr(path.node.source.value.lastIndexOf('.')) : null;
if (extension !== '.css' && Object.keys(stats.opts.filetypes).indexOf(extension) < 0) {
return true;
}
const filename = getTargetResourcePath(path, stats);
if (stats.opts.exclude && isFilenameExcluded(filename, stats.opts.exclude)) {
return true;
}
return false;
};
return {
inherits: babelPluginJsxSyntax,
visitor: {
ImportDeclaration (path: *, stats: *): void {
if (skip || notForPlugin(path, stats)) {
return;
}
const filename = stats.file.opts.filename;
const targetResourcePath = getTargetResourcePath(path, stats);
let styleImportName: string;
if (path.node.specifiers.length === 0) {
// use imported file path as import name
styleImportName = path.node.source.value;
} else if (path.node.specifiers.length === 1) {
styleImportName = path.node.specifiers[0].local.name;
} else {
// eslint-disable-next-line no-console
console.warn('Please report your use case. https://github.com/gajus/babel-plugin-react-css-modules/issues/new?title=Unexpected+use+case.');
throw new Error('Unexpected use case.');
}
filenameMap[filename].styleModuleImportMap[styleImportName] = requireCssModule(targetResourcePath, {
context: stats.opts.context,
filetypes: stats.opts.filetypes || {},
generateScopedName: stats.opts.generateScopedName
});
if (stats.opts.webpackHotModuleReloading) {
addWebpackHotModuleAccept(path);
}
if (stats.opts.removeImport) {
path.remove();
}
},
JSXElement (path: *, stats: *): void {
if (skip) {
return;
}
const filename = stats.file.opts.filename;
if (stats.opts.exclude && isFilenameExcluded(filename, stats.opts.exclude)) {
return;
}
let attributeNames = optionsDefaults.attributeNames;
if (stats.opts && stats.opts.attributeNames) {
attributeNames = Object.assign({}, attributeNames, stats.opts.attributeNames);
}
const attributes = path.node.openingElement.attributes
.filter((attribute) => {
return typeof attribute.name !== 'undefined' && typeof attributeNames[attribute.name.name] === 'string';
});
if (attributes.length === 0) {
return;
}
const {
handleMissingStyleName = optionsDefaults.handleMissingStyleName,
autoResolveMultipleImports = optionsDefaults.autoResolveMultipleImports
} = stats.opts || {};
for (const attribute of attributes) {
const destinationName = attributeNames[attribute.name.name];
const options = {
autoResolveMultipleImports,
handleMissingStyleName
};
if (t.isStringLiteral(attribute.value)) {
resolveStringLiteral(
path,
filenameMap[filename].styleModuleImportMap,
attribute,
destinationName,
options
);
} else if (t.isJSXExpressionContainer(attribute.value)) {
if (!filenameMap[filename].importedHelperIndentifier) {
setupFileForRuntimeResolution(path, filename);
}
replaceJsxExpressionContainer(
t,
path,
attribute,
destinationName,
filenameMap[filename].importedHelperIndentifier,
filenameMap[filename].styleModuleImportMapIdentifier,
options
);
}
}
},
Program (path: *, stats: *): void {
if (!validate(stats.opts)) {
// eslint-disable-next-line no-console
console.error(validate.errors);
throw new Error('Invalid configuration');
}
const filename = stats.file.opts.filename;
filenameMap[filename] = {
styleModuleImportMap: {}
};
if (stats.opts.skip && !attributeNameExists(path, stats)) {
skip = true;
}
}
}
};
};