forked from vuejs/rollup-plugin-vue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvueTransform.js
244 lines (194 loc) · 7.31 KB
/
vueTransform.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
import deIndent from 'de-indent'
import htmlMinifier from 'html-minifier'
import parse5 from 'parse5'
import templateValidator from 'vue-template-validator'
import { compile } from './style/index'
import templateProcessor from './template/index'
import { relative } from 'path'
import MagicString from 'magic-string'
import debug from './debug'
import { injectModule, injectScopeID, injectTemplate, injectRender } from './injections'
import genScopeID from './gen-scope-id'
function getNodeAttrs (node) {
if (node.attrs) {
const attributes = {}
for (const attr of node.attrs) {
attributes[attr.name] = attr.value
}
return attributes
}
return {}
}
/**
* Pad content with empty lines to get correct line number in errors.
*/
function padContent (content) {
return content
.split(/\r?\n/g)
.map(() => '')
.join('\n')
}
function validateTemplate (code, content, id) {
const warnings = templateValidator(code, content)
if (Array.isArray(warnings)) {
const relativePath = relative(process.cwd(), id)
warnings.forEach((msg) => {
console.warn(`\n Warning in ${relativePath}:\n ${msg}`)
})
}
}
/**
* Compile template: DeIndent and minify html.
*/
async function processTemplate (source, id, content, options, nodes, modules) {
if (source === undefined) return undefined
debug(`Process template: ${id}`)
const extras = { modules, id, lang: source.attrs.lang }
const code = deIndent(source.code)
const template = await (
options.disableCssModuleStaticReplacement !== true
? templateProcessor(code, extras, options)
: code
)
if (!options.compileTemplate) {
validateTemplate(code, content, id)
}
return htmlMinifier.minify(template, options.htmlMinifier)
}
async function processScript (source, id, content, options, nodes, modules, scoped) {
const template = await processTemplate(nodes.template[0], id, content, options, nodes, modules)
debug(`Process script: ${id}`)
const lang = 'js'
if (source.attrs.lang && ['js', 'babel'].indexOf(source.attrs.lang) < 0) {
if (!(source.attrs.lang in options.script)) {
throw new Error(`[rollup-plugin-vue] ${source.attrs.lang} is not yet supported in .vue files.`)
}
source = await options.script[source.attrs.lang](source, id, content, options, nodes)
}
let script = deIndent(padContent(content.slice(0, content.indexOf(source.code))) + source.code)
const map = (new MagicString(script)).generateMap({ hires: true })
script = processScriptForStyle(script, modules, scoped, lang, id, options)
script = await processScriptForRender(script, template, lang, id, options)
return { map, code: script }
}
function processScriptForStyle (script, modules, scoped, lang, id, options) {
script = injectModule(script, modules, lang, id, options)
if (scoped) {
const scopeID = genScopeID(id)
script = injectScopeID(script, scopeID, lang, id, options)
}
return script
}
async function processScriptForRender (script, template, lang, id, options) {
if (template && options.compileTemplate) {
const render = require('vue-template-compiler').compile(template, options.compileOptions)
return await injectRender(script, render, lang, id, options)
}
if (template) {
return await injectTemplate(script, template, lang, id, options)
}
return script
}
// eslint-disable-next-line complexity
async function processStyle (styles, id, content, options) {
debug(`Process styles: ${id}`)
const outputs = []
for (let i = 0; i < styles.length; i += 1) {
const style = styles[i]
const code = deIndent(
padContent(content.slice(0, content.indexOf(style.code))) + style.code
)
const map = (new MagicString(code)).generateMap({ hires: true })
const output = {
id,
code: code,
map: map,
lang: style.attrs.lang || 'css',
module: 'module' in style.attrs ? style.attrs.module || true : false,
scoped: 'scoped' in style.attrs ? style.attrs.scoped || true : false
}
outputs.push(options.autoStyles ? await compile(output, options) : output)
}
return outputs
}
function parseTemplate (code) {
debug('Parsing template....')
const fragment = parse5.parseFragment(code, { locationInfo: true })
const nodes = {
template: [],
script: [],
style: []
}
for (let i = fragment.childNodes.length - 1; i >= 0; i -= 1) {
const name = fragment.childNodes[i].nodeName
if (!(name in nodes)) {
continue
}
const start = fragment.childNodes[i].__location.startTag.endOffset
const end = fragment.childNodes[i].__location.endTag.startOffset
nodes[name].push({
node: fragment.childNodes[i],
code: code.substr(start, end - start),
attrs: getNodeAttrs(fragment.childNodes[i])
})
}
if (nodes.script.length === 0) {
nodes.script.push({
node: null,
code: 'export default {\n}',
attrs: {}
})
}
return nodes
}
const getModules = function (styles) {
let all = {}
for (let i = 0; i < styles.length; i += 1) {
const style = styles[i]
if (style.module) {
all = Object.assign(all, style.$compiled.module)
}
}
return all
}
const hasScoped = function (styles) {
return styles.reduce((scoped, style) => {
return scoped || style.scoped
}, false)
}
export default async function vueTransform (code, id, options) {
const nodes = parseTemplate(code)
const css = await processStyle(nodes.style, id, code, options, nodes)
const modules = getModules(css)
const scoped = hasScoped(css)
const js = await processScript(nodes.script[0], id, code, options, nodes, modules, scoped)
const isProduction = process.env.NODE_ENV === 'production'
const isWithStripped = options.stripWith !== false
if (!isProduction && !isWithStripped) {
js.code = js.code + '\nmodule.exports.render._withStripped = true'
}
if (options.styleToImports === true) {
const style = css.map((s, i) => 'import ' + JSON.stringify(`${id}.${i}.vue.component.${s.lang}`) + ';').join(' ')
return { css, code: style + js.code, map: js.map }
} else if (options.css === true) {
const style = css.map(s => '$compiled' in s ? s.$compiled.code : s.code).join('\n').replace(/(\r?\n|[\s])+/g, ' ')
const styleCode = `
(function(){
if(document){
var head=document.head||document.getElementsByTagName('head')[0],
style=document.createElement('style'),
css=${JSON.stringify(style)};
style.type='text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
})();
`.replace(/(\r?\n|[\s])+/g, ' ').trim()
return { css, code: styleCode + js.code, map: js.map }
}
return { css, code: js.code, map: js.map }
}