-
Notifications
You must be signed in to change notification settings - Fork 6
/
get-metro-android-assets-resolution-fix.js
53 lines (50 loc) · 1.92 KB
/
get-metro-android-assets-resolution-fix.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
// Unfortunately, there's an issue with assets resolution on android when
// importing assets from paths outside of the project's root directory.
// To fix it, we can patch metro's `publicPath` and `enhanceMiddleware` to
// allow reading from `n` depths below the project directory.
// For our use case, "4" is enough (to account for `../core/src`) but you might
// wanna bump it up if you need to shuffle the assets location.
// For more info, see this metro comment:
// https://github.com/facebook/metro/issues/290#issuecomment-543746458
/**
* @typedef {Object} MetroAndroidAssetFix
* @prop {string} publicPath - Metro's `publicPath`.
* @prop {function} applyMiddleware - Function that applies the patch middleware to metro.
*/
/**
* Return the Metro Android assets resolution fix.
* @param {object} params - Input parameters
* @param {number} [params.depth = 4] - `n` depth below the project directory.
* @returns {MetroAndroidAssetFix} Metro Android assets resolution fix.
*/
module.exports = function getMetroAndroidAssetsResolutionFix(params = {}) {
const { depth = 4 } = params;
let publicPath = generateAssetsPath(depth, "dir");
const applyMiddleware = (middleware) => {
return (req, res, next) => {
for (let currentDepth = depth; currentDepth >= 0; currentDepth--) {
const pathToReplace = generateAssetsPath(currentDepth, "dir");
const replacementPath = generateAssetsPath(depth - currentDepth, "..");
if (currentDepth === depth) {
publicPath = pathToReplace;
}
if (req.url.startsWith(pathToReplace)) {
req.url = req.url.replace(pathToReplace, replacementPath);
break;
}
}
return middleware(req, res, next);
};
};
return {
publicPath,
applyMiddleware,
};
};
function generateAssetsPath(depth, subpath) {
return `/assets`.concat(
Array.from({ length: depth })
.map(() => `/${subpath}`)
.join("")
);
}