forked from gajus/babel-plugin-react-css-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetClassName.js
65 lines (51 loc) · 1.92 KB
/
getClassName.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
// @flow
import type {
StyleModuleMapType,
StyleModuleImportMapType
} from './types';
const isNamespacedStyleName = (styleName: string): boolean => {
return styleName.indexOf('.') !== -1;
};
const getClassNameForNamespacedStyleName = (styleName: string, styleModuleImportMap: StyleModuleImportMapType): string => {
// Note:
// Do not use the desctructing syntax with Babel.
// Desctructing adds _slicedToArray helper.
const styleNameParts = styleName.split('.');
const importName = styleNameParts[0];
const moduleName = styleNameParts[1];
if (!moduleName) {
throw new Error('Invalid style name.');
}
if (!styleModuleImportMap[importName]) {
throw new Error('CSS module import does not exist.');
}
if (!styleModuleImportMap[importName][moduleName]) {
throw new Error('CSS module does not exist.');
}
return styleModuleImportMap[importName][moduleName];
};
export default (styleNameValue: string, styleModuleImportMap: StyleModuleImportMapType): string => {
const styleModuleImportMapKeys = Object.keys(styleModuleImportMap);
return styleNameValue
.split(' ')
.filter((styleName) => {
return styleName;
})
.map((styleName) => {
if (isNamespacedStyleName(styleName)) {
return getClassNameForNamespacedStyleName(styleName, styleModuleImportMap);
}
if (styleModuleImportMapKeys.length === 0) {
throw new Error('Cannot use styleName attribute without importing at least one stylesheet.');
}
if (styleModuleImportMapKeys.length > 1) {
throw new Error('Cannot use anonymous style name with more than one stylesheet import.');
}
const styleModuleMap: StyleModuleMapType = styleModuleImportMap[styleModuleImportMapKeys[0]];
if (!styleModuleMap[styleName]) {
throw new Error('Could not resolve the styleName \'' + styleName + '\'.');
}
return styleModuleMap[styleName];
})
.join(' ');
};