forked from GetStream/stream-chat-react-native
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrollup-react-native-image.js
70 lines (63 loc) · 2.06 KB
/
rollup-react-native-image.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
/* eslint-env node */
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import path from 'path';
export default function reactNativeImage(options = {}) {
const includedImages = [];
const extensions = options.extensions || [
'.jpg',
'.jpeg',
'.png',
'.gif',
'.svg',
];
let sourceDir = options.sourceDir || __dirname;
if (sourceDir[sourceDir.length - 1] !== path.sep) {
sourceDir += path.sep;
}
function toFileName(id) {
if (id.startsWith(sourceDir)) {
return id.slice(sourceDir.length - 1);
}
return path.basename(id);
}
return {
load: (id) => {
if (!extensions.includes(path.extname(id))) {
return null;
}
if (!includedImages.includes(id)) {
includedImages.push(id);
}
return `const img = require('./${toFileName(id)}'); export default img;`;
},
name: 'react-native-image',
ongenerate: (options) => {
for (const image of includedImages) {
const origFileName = toFileName(image);
const origSourceDir = image.slice(0, -origFileName.length + 1);
const origDestDir = path.dirname(options.dest || options.file);
const origDestPath = path.join(origDestDir, origFileName);
const fullDestDir = path.dirname(origDestPath);
if (!existsSync(fullDestDir)) {
mkdirSync(fullDestDir, { recursive: true });
}
writeFileSync(origDestPath, readFileSync(image));
const extension = path.extname(origDestPath);
const base = path.basename(origDestPath, extension);
const dir = path.dirname(origFileName);
for (let i = 1; i < 6; i++) {
const scaledFileName = path.join(
dir,
base + '@' + i + 'x' + extension,
);
const scaledPath = path.join(origSourceDir, scaledFileName);
const scaledDestPath = path.join(origDestDir, scaledFileName);
if (!existsSync(scaledPath)) {
continue;
}
writeFileSync(scaledDestPath, readFileSync(scaledPath));
}
}
},
};
}