-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathgenerate-index.js
79 lines (71 loc) · 2.2 KB
/
generate-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
77
78
79
#!/usr/bin/env node
'use strict'
const fs = require('fs')
const path = require('path')
require('babel-core/register')
const autoInject = require('../lib/autoInject').default
generateIndex(err => {
if (err) throw err
})
function generateIndex(done) {
autoInject({
entries: cb => readEntries(cb),
aliases: cb => loadAliases(cb),
template: cb => fs.readFile(path.join(__dirname, './index-template.js'), 'utf8', cb),
generated: (entries, aliases, template, cb) => {
cb(null, renderTemplate(entries, aliases, template))
}
}, (err, results) => {
if (err) return done(err)
console.log(results.generated)
done()
})
}
function loadAliases (cb) {
const aliases = {}
fs.readFileSync(path.join(__dirname, 'aliases.txt'), 'utf8')
.split('\n')
.filter(Boolean)
.forEach(line => {
const [alias, src] = line.split(' ')
aliases[alias] = src
})
cb(null, aliases)
}
function readEntries (cb) {
const libDir = path.join(__dirname, '../lib')
fs.readdir(libDir, (err, files) => {
if (err) return cb(err)
cb(null, files
.map(file => path.basename(file, '.js'))
.filter(file => !file.match(/(^(index|internal)$)/)))
})
}
function renderTemplate(entries, aliases, template) {
return template
.replace(
`/*__imports__*/`,
entries
.map(entry => `import ${entry} from './${entry}'`)
.join('\n'))
.replace(
`/*__default_object__*/`,
entries
.map(entry => ` ${entry}`)
.join(',\n') + ',')
.replace(
`/*__default_aliases__*/`,
Object.keys(aliases)
.map(alias => ` ${alias}: ${aliases[alias]}`)
.join(',\n'))
.replace(
`/*__exports__*/`,
entries
.map(entry => ` ${entry} as ${entry}`)
.join(',\n') + ',')
.replace(
`/*__alias_exports__*/`,
Object.keys(aliases)
.map(alias => ` ${aliases[alias]} as ${alias}`)
.join(',\n'))
}