forked from kristerkari/react-native-less-transformer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (60 loc) · 2.17 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
var less = require("less");
var semver = require("semver");
var path = require("path");
var appRoot = require("app-root-path");
var css2rn = require("css-to-react-native-transform").default;
var upstreamTransformer = null;
var reactNativeVersionString = require("react-native/package.json").version;
var reactNativeMinorVersion = semver(reactNativeVersionString).minor;
if (reactNativeMinorVersion >= 59) {
upstreamTransformer = require("metro-react-native-babel-transformer");
} else if (reactNativeMinorVersion >= 56) {
upstreamTransformer = require("metro/src/reactNativeTransformer");
} else if (reactNativeMinorVersion >= 52) {
upstreamTransformer = require("metro/src/transformer");
} else if (reactNativeMinorVersion >= 47) {
upstreamTransformer = require("metro-bundler/src/transformer");
} else if (reactNativeMinorVersion === 46) {
upstreamTransformer = require("metro-bundler/build/transformer");
} else {
// handle RN <= 0.45
var oldUpstreamTransformer = require("react-native/packager/transformer");
upstreamTransformer = {
transform({ src, filename, options }) {
return oldUpstreamTransformer.transform(src, filename, options);
}
};
}
function renderToCSS({ src, filename, options = {} }) {
var { lessOptions = {} } = options;
var lessPromise = new Promise((resolve, reject) => {
less
.render(src, { paths: [path.dirname(filename), appRoot], ...lessOptions })
.then(result => {
resolve(result.css);
})
.catch(reject);
});
return lessPromise;
}
function renderCSSToReactNative(css) {
return css2rn(css, { parseMediaQueries: true });
}
module.exports.transform = function(src, filename, options) {
if (typeof src === "object") {
// handle RN >= 0.46
({ src, filename, options } = src);
}
if (filename.endsWith(".less")) {
return renderToCSS({ src, filename, options }).then(css => {
var cssObject = renderCSSToReactNative(css);
return upstreamTransformer.transform({
src: "module.exports = " + JSON.stringify(cssObject),
filename,
options
});
});
}
return upstreamTransformer.transform({ src, filename, options });
};
module.exports.renderToCSS = renderToCSS;