forked from couetilc/react-social-icons
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrollup-plugin-social-icons.js
60 lines (51 loc) · 1.48 KB
/
rollup-plugin-social-icons.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
/* eslint-env node */
import fs from 'fs'
const VIRTUAL_PKG = 'social-icons'
const IMPORT_PREFIX = `\0${VIRTUAL_PKG}`
export default function rollupPluginSocialIcons() {
const db = new Map()
return {
name: 'social-icons',
async buildStart() {
const dbFiles = await fs.promises.readdir(
new URL('./db', import.meta.url),
)
await Promise.all(
dbFiles.map((filename) =>
fs.promises
.readFile(new URL(`./db/${filename}`, import.meta.url))
.then((icon) => {
const network = filename.replace('.json', '')
db.set(network, JSON.parse(icon.toString()))
}),
),
)
},
resolveId(source) {
if (source.startsWith(VIRTUAL_PKG)) {
return `\0${source}`
}
return null
},
load(id) {
if (!id.startsWith(IMPORT_PREFIX)) {
return null
}
if (id === IMPORT_PREFIX) {
const code = Array.from(db.keys()).reduce((file, network) => {
return `${file}export { default as ${JSON.stringify(
network.replace(/\W/u, ''),
)} } from '${VIRTUAL_PKG}:${network}';`
}, '')
return { code, moduleSideEffects: true }
}
const network = id.replace(`${IMPORT_PREFIX}:`, '')
return `
import { register } from './src/component.jsx';
export default register(${JSON.stringify(network)}, ${JSON.stringify(
db.get(network),
)});
`
},
}
}