-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.js
260 lines (183 loc) · 6.89 KB
/
convert.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#!/usr/bin/env node
const glob = require('glob')
const fs = require('fs')
const compiler = require('vue-template-compiler')
const sass = require('node-sass')
const postcss = require('postcss')
const path = require('path')
const minimist = require('minimist')
const htmlparser = require('node-html-parser')
// options
const args = minimist(process.argv.slice(2))
const opts = {
entry: '',
publicPath: '',
ignore: ['node_modules/**'],
noscope: false,
alias: {},
dest: 'dist'
}
opts.entry = args.entry != undefined ? path.relative('./', args.entry) : opts.entry
opts.publicPath = args.publicPath != undefined ? path.relative('./', args.publicPath) : opts.entry
opts.ignore = args.ignore ? opts.ignore.concat(args.ignore.split(',')) : opts.ignore
opts.noscope = args.noscope ? args.noscope : opts.noscope
opts.dest = args.dest != undefined ? path.relative('./', args.dest) : opts.dest
opts.alias = args.alias
? Object.fromEntries(args.alias.split(',').map(a => a.split(':')))
: opts.alias
const tab = ' '
const pattern = (opts.entry ? opts.entry + '/' : '') + '/**/*.vue'
const files = glob.sync(pattern, { ignore: opts.ignore })
files.forEach(file => {
const pathParse = path.parse(file)
const dirRelativeToEntry = path.relative(opts.entry, pathParse.dir)
const outDir = opts.dest + '/' + dirRelativeToEntry
const dirRelativeToPublic = path.relative(opts.publicPath, outDir)
const outPath = outDir + '/' + pathParse.name
const scopeSelectors = []
let warnings = []
fs.readFile(file, 'utf8', async (err, content) => {
if (err) return console.error(err)
// parse
const parsed = compiler.parseComponent(content)
// extract
// script & style
let script = parsed.script ? parsed.script.content.trim() : ''
let styles = '' // styles will be filled later
// template
let template = ''
if (parsed.template && parsed.template.content.trim()) {
template = parsed.template.content.trim()
}
else if (script) {
// there is no template block, but there is script
// maybe template is in js
const match = script.match(/(.|\n)*template:\s*([\`'"])/m)
if (match) {
// template is in js
// extract it
template = script.replace(match[0], '')
const quote = match[0].slice(-1)
let regex = new RegExp('(?<!\\\\)\\'+quote+'(.|\\n)*','m')
template = template.replace(regex, '')
// remove template from script (it will get injected back later)
regex = new RegExp('template:\\s*'+quote+'(.|\\n)*(?<!\\\\)'+quote+',?\\s*', 'm')
script = script.replace(regex, '')
}
}
// process
// styles
if (parsed.styles && parsed.styles.length) {
for (let parsedStyle of parsed.styles) {
let style = parsedStyle.content.trim()
if (parsedStyle.lang && parsedStyle.lang == 'scss') {
// scss -> css
style = sass.renderSync({
data: style,
outputStyle: 'expanded'
}).css.toString()
}
if (parsedStyle.scoped && template && !opts.noscope) {
// scoped
// generate scope name from filename
const scope = file
.replace(/\.vue$/, '')
.replace(/[\/.]/g, '-')
// add scope to css selectors
style = await postcss().use(root => {
root.walkRules(rule => {
scopeSelectors.push(rule.selector)
const selectors = rule.selector.match(/(^|[\.#\s])[\w\-]+/g)
selectors.forEach(s => {
rule.selector = rule.selector.replace(s, s+'[data-scope-'+scope+']')
})
})
}).process(style, { from: undefined }).then(result => result.css)
// add scope to template items
const html = htmlparser.parse(template)
scopeSelectors.forEach(selector => {
// only add scope attribute to elements that are styled from scoped css
const els = html.querySelectorAll(selector)
for (let el of els) {
for (let a of Object.keys(el.attributes)) {
if (a.includes('data-scope-')) {
el.removeAttribute(a)
}
}
el.setAttribute('data-scope-'+scope, '')
}
})
template = html.toString()
// remove ="" for prettiness
const regex = new RegExp('(data-scope-'+scope+')=""','g')
template = template.replace(regex, '$1')
} else if (!template && !opts.noscope) {
warnings.push('scoped style, but no template')
}
// join all styles
styles += style + '\n'
}
if (script) {
// add style attachment to script
script += '\n\n// attach styles\nfetch(\''+dirRelativeToPublic+'/'+pathParse.name+'.css\').then(res => res.text()).then(style => document.head.insertAdjacentHTML(\'beforeend\', \'<style>\'+style+\'</style>\'))'
}
} else {
warnings.push('no style')
}
// template -> script
if (template && script) {
// backslash any unbackslashed occurancies of `
template = template.trim().replace(/(?<!\\)`/g, '\`')
const templateString = 'template: `\n' + template + '`,'
const match = script.match(/(export\sdefault\s*\{)/)
if (match) {
// there is a default export, append template to it
script = script.replace(
match[0], match[0] + '\n' + tab + templateString
)
} else {
warnings.push('can\'t find default export')
}
} else {
warnings.push('no script or template')
}
// script
if (script) {
// rewrite imports
// alias
for (let a in opts.alias) {
const regexAlias = new RegExp('(import.*from [\'"].*)'+a+'(.*[\'"])', 'g')
const match = script.match(regexAlias)
if (match) {
match.forEach(statement => {
let newStatement = statement.replace(a, opts.alias[a])
const absPath = newStatement.match(/(import.*)['"](.*)(['"])/)[2]
const relPath = path.relative(pathParse.dir, absPath)
newStatement = newStatement.replace(absPath, './'+relPath)
script = script.replace(statement, newStatement)
})
}
}
// vue -> js
script = script.replace(/(import.*)\.vue(['"])/g, '$1.js$2')
}
// write files
fs.mkdir(outDir, { recursive: true }, (err) => {
if (err) return console.log(err)
if (script) {
fs.writeFile(outPath+'.js', script, err => {
if (err) return console.log(err)
})
}
if (styles) {
fs.writeFile(outPath+'.css', styles, err => {
if (err) return console.log(err)
})
}
})
// log warnings
if (warnings.length) {
warnings.forEach(w => console.log('\x1b[33m%s\x1b[0m', 'WARN! '+file+' : '+ w))
}
})
})