forked from codebandits/react-app-rewire-css-modules
-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
76 lines (66 loc) · 2.01 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
const path = require("path");
const { getLoader, loaderNameMatches } = require("react-app-rewired");
const lessExtension = /\.less$/;
const lessModuleExtension = /\.module.less$/;
function createRewireLess(lessLoaderOptions = {}) {
return function(config, env) {
// Exclude all less files (including module files) from file-loader
const fileLoader = getLoader(config.module.rules, rule => {
return loaderNameMatches(rule, "file-loader") && rule.exclude;
});
fileLoader.exclude.push(lessExtension);
const createRule = (rule, cssRules) => {
if (env === "production") {
return {
...rule,
loader: [
...cssRules.loader,
{ loader: "less-loader", options: lessLoaderOptions },
],
};
} else {
return {
...rule,
use: [
...cssRules.use,
{ loader: "less-loader", options: lessLoaderOptions },
],
};
}
};
const lessRules = createRule(
{
test: lessExtension,
exclude: lessModuleExtension,
},
// Get a copy of the CSS loader
getLoader(
config.module.rules,
rule => String(rule.test) === String(/\.css$/),
),
);
const lessModuleRules = createRule(
{ test: lessModuleExtension },
// Get a copy of the CSS module loader
getLoader(
config.module.rules,
rule => String(rule.test) === String(/\.module\.css$/),
),
);
const oneOfRule = config.module.rules.find(
rule => rule.oneOf !== undefined,
);
if (oneOfRule) {
oneOfRule.oneOf.unshift(lessRules);
oneOfRule.oneOf.unshift(lessModuleRules);
} else {
// Fallback to previous behaviour of adding to the end of the rules list.
config.module.rules.push(lessRules);
config.module.rules.push(lessModuleRules);
}
return config;
};
}
const rewireLess = createRewireLess();
rewireLess.withLoaderOptions = createRewireLess;
module.exports = rewireLess;