forked from vuejs/rollup-plugin-vue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
485 lines (427 loc) · 13.6 KB
/
index.ts
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
import {
createVueFilter,
createVuePartRequest,
parseVuePartRequest,
resolveVuePart,
isVuePartRequest,
transformRequireToImport
} from './utils'
import {
createDefaultCompiler,
assemble,
ScriptOptions,
StyleOptions,
TemplateOptions,
StyleCompileResult,
DescriptorCompileResult
} from '@vue/component-compiler'
import MagicString from 'magic-string'
import { Plugin, RawSourceMap } from 'rollup'
import * as path from 'path'
import { parse, SFCDescriptor, SFCBlock } from '@vue/component-compiler-utils'
import debug from 'debug'
import {
VueTemplateCompiler,
VueTemplateCompilerParseOptions
} from '@vue/component-compiler-utils/dist/types'
const templateCompiler = require('vue-template-compiler')
const hash = require('hash-sum')
const { version } = require('../package.json')
const d = debug('rollup-plugin-vue')
const dR = debug('rollup-plugin-vue:resolve')
const dL = debug('rollup-plugin-vue:load')
const dT = debug('rollup-plugin-vue:transform')
export interface VuePluginOptionsData {
css: string | (() => string)
less: string | (() => string)
postcss: string | (() => string)
sass: string | (() => string)
scss: string | (() => string)
stylus: string | (() => string)
}
export interface VuePluginOptions {
/**
* Include files or directories.
* @default `'.vue'`
*/
include?: Array<string | RegExp> | string | RegExp
/**
* Exclude files or directories.
* @default `undefined`
*/
exclude?: Array<string | RegExp> | string | RegExp
/**
* Default language for blocks.
*
* @default `{}`
* @example
* ```js
* VuePlugin({ defaultLang: { script: 'ts' } })
* ```
*/
defaultLang?: {
[key: string]: string
}
/**
* Exclude/Include customBlocks for final build.
* @default `() => false`
* @example
* ```js
* VuePlugin({ customBlocks: ['markdown', '!test'] })
* ```
*/
customBlocks?: string[] | ((tag: string) => boolean)
/**
* Exclude customBlocks for final build.
* @default `['*']`
* @deprecated
* @example
* ```js
* VuePlugin({ blackListCustomBlocks: ['markdown', 'test'] })
* ```
*/
blackListCustomBlocks?: string[]
/**
* Include customBlocks for final build.
* @default `[]`
* @deprecated
* @example
* ```js
* VuePlugin({ blackListCustomBlocks: ['markdown', 'test'] })
* ```
*/
whiteListCustomBlocks?: string[]
/**
* Prepend CSS.
* @default `undefined`
* @example
* ```js
* VuePlugin({ data: { scss: '$color: red;' } }) // to extract css
* ```
*/
data?: Partial<VuePluginOptionsData>
/**
* Inject CSS in JavaScript.
* @default `true`
* @example
* ```js
* VuePlugin({ css: false }) // to extract css
* ```
*/
css?: boolean
/**
* Expose filename in __file property.
* @default `false`
* @example
* ```js
* VuePlugin({ exposeFilename: true })
* ```
*/
exposeFilename?: boolean
compiler?: VueTemplateCompiler
compilerParseOptions?: VueTemplateCompilerParseOptions
sourceRoot?: string
/**
* @@vue/component-compiler [#](https://github.com/vuejs/vue-component-compiler#api) script processing options.
*/
script?: ScriptOptions
/**
* @@vue/component-compiler [#](https://github.com/vuejs/vue-component-compiler#api) style processing options.
*/
style?: StyleOptions
/**
* @@vue/component-compiler [#](https://github.com/vuejs/vue-component-compiler#api) template processing options.
*/
template?: TemplateOptions
/**
* @@vue/component-compiler [#](https://github.com/vuejs/vue-component-compiler#api) module name or global function for custom runtime component normalizer.
*/
normalizer?: string
/**
* @@vue/component-compiler [#](https://github.com/vuejs/vue-component-compiler#api) module name or global function for custom style injector factory.
*/
styleInjector?: string
/**
* @@vue/component-compiler [#](https://github.com/vuejs/vue-component-compiler#api) module name or global function for custom style injector factory for SSR environment.
*/
styleInjectorSSR?: string
beforeAssemble?(descriptor: DescriptorCompileResult): DescriptorCompileResult
}
/**
* Rollup plugin for handling .vue files.
*/
export default function vue(opts: Partial<VuePluginOptions> = {}): Plugin {
const isVue = createVueFilter(opts.include, opts.exclude)
const isProduction =
opts.template && typeof opts.template.isProduction === 'boolean'
? opts.template.isProduction
: process.env.NODE_ENV === 'production' ||
process.env.BUILD === 'production'
d('Version ' + version)
d(`Build environment: ${isProduction ? 'production' : 'development'}`)
d(`Build target: ${process.env.VUE_ENV || 'browser'}`)
if (!opts.normalizer)
opts.normalizer = '~' + 'vue-runtime-helpers/dist/normalize-component.js'
if (!opts.styleInjector)
opts.styleInjector =
'~' + 'vue-runtime-helpers/dist/inject-style/browser.js'
if (!opts.styleInjectorSSR)
opts.styleInjectorSSR =
'~' + 'vue-runtime-helpers/dist/inject-style/server.js'
createVuePartRequest.defaultLang = {
...createVuePartRequest.defaultLang,
...opts.defaultLang
}
const shouldExtractCss = opts.css === false
const customBlocks: string[] = []
if (opts.blackListCustomBlocks) {
console.warn(
'`blackListCustomBlocks` option is deprecated use `customBlocks`. See https://rollup-plugin-vue.vuejs.org/options.html#customblocks.'
)
customBlocks.push(...opts.blackListCustomBlocks.map(tag => '!' + tag))
}
if (opts.whiteListCustomBlocks) {
console.warn(
'`whiteListCustomBlocks` option is deprecated use `customBlocks`. See https://rollup-plugin-vue.vuejs.org/options.html#customblocks.'
)
customBlocks.push(...opts.whiteListCustomBlocks)
}
const isAllowed = createCustomBlockFilter(opts.customBlocks || customBlocks)
const beforeAssemble =
opts.beforeAssemble ||
((d: DescriptorCompileResult): DescriptorCompileResult => d)
const exposeFilename =
typeof opts.exposeFilename === 'boolean' ? opts.exposeFilename : false
const data: VuePluginOptionsData = (opts.data || {}) as any
delete opts.data
delete opts.beforeAssemble
delete opts.css
delete opts.exposeFilename
delete opts.customBlocks
delete opts.blackListCustomBlocks
delete opts.whiteListCustomBlocks
delete opts.defaultLang
delete opts.include
delete opts.exclude
opts.template = {
transformAssetUrls: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
},
...opts.template
} as any
if (opts.template && typeof opts.template.isProduction === 'undefined') {
opts.template.isProduction = isProduction
}
const compiler = createDefaultCompiler(opts)
const descriptors = new Map<string, SFCDescriptor>()
if (opts.css === false) d('Running in CSS extract mode')
function prependStyle(
id: string,
lang: string,
code: string,
map: any
): { code: string } {
if (!(lang in data)) return { code }
const ms = new MagicString(code, {
filename: id,
indentExclusionRanges: []
})
const value: string | (() => string) = (data as any)[lang]
const fn = typeof value === 'function' ? value : () => value
ms.prepend(fn())
return { code: ms.toString() }
}
return {
name: 'VuePlugin',
resolveId(id, importer) {
const request = id
if (id.startsWith('vue-runtime-helpers/')) {
id = require.resolve(id)
dR(`form: ${request} \nto: ${id}\n`)
return id
}
if (!isVuePartRequest(id)) return
id = path.resolve(path.dirname(importer), id)
const ref = parseVuePartRequest(id)
if (ref) {
const element = resolveVuePart(descriptors, ref)
const src = (element as SFCBlock).src
if (ref.meta.type !== 'styles' && typeof src === 'string') {
if (src.startsWith('.')) {
return path.resolve(path.dirname(ref.filename), src as string)
} else {
return require.resolve(src, {
paths: [path.dirname(ref.filename)]
})
}
}
dR(`from: ${request} \nto: ${id}\n`)
return id
}
},
load(id: string) {
const request = parseVuePartRequest(id)
if (!request) return null
const element = resolveVuePart(descriptors, request)
let code =
'code' in element
? ((element as any).code as string) // .code is set when extract styles is used. { css: false }
: element.content
let map = element.map as RawSourceMap
if (request.meta.type === 'styles') {
code = prependStyle(id, request.meta.lang, code, map).code
}
dL(`id: ${id}\ncode: \n${code}\nmap: ${JSON.stringify(map, null, 2)}\n\n`)
return { code, map }
},
async transform(source: string, filename: string) {
if (isVue(filename)) {
// Create deep copy to prevent issue during watching changes.
const descriptor: SFCDescriptor = JSON.parse(
JSON.stringify(
parse({
filename,
source,
compiler: opts.compiler || templateCompiler,
compilerParseOptions: opts.compilerParseOptions,
sourceRoot: opts.sourceRoot,
needMap: 'needMap' in opts ? (opts as any).needMap : true
})
)
)
descriptors.set(filename, descriptor)
const scopeId =
'data-v-' +
(isProduction
? hash(path.basename(filename) + source)
: hash(filename + source))
const styles = await Promise.all(
descriptor.styles.map(async style => {
if (style.content) {
style.content = prependStyle(
filename,
style.lang || 'css',
style.content,
style.map
).code
}
const compiled = await compiler.compileStyleAsync(
filename,
scopeId,
style
)
if (compiled.errors.length > 0) throw Error(compiled.errors[0])
return compiled
})
)
const input: any = {
scopeId,
styles,
customBlocks: []
}
if (descriptor.template) {
input.template = compiler.compileTemplate(
filename,
descriptor.template
)
input.template.code = transformRequireToImport(input.template.code)
if (input.template.errors && input.template.errors.length) {
input.template.errors.map((error: Error) => this.error(error))
}
if (input.template.tips && input.template.tips.length) {
input.template.tips.map((message: string) => this.warn({ message }))
}
}
input.script = descriptor.script
? {
code: `
export * from '${createVuePartRequest(
filename,
descriptor.script.lang || 'js',
'script'
)}'
import script from '${createVuePartRequest(
filename,
descriptor.script.lang || 'js',
'script'
)}'
export default script
${
exposeFilename
? `
// For security concerns, we use only base name in production mode. See https://github.com/vuejs/rollup-plugin-vue/issues/258
script.__file = ${
isProduction
? JSON.stringify(path.basename(filename))
: JSON.stringify(filename)
}`
: ''
}
`
}
: { code: '' }
if (shouldExtractCss) {
input.styles = input.styles
.map((style: StyleCompileResult, index: number) => {
;(descriptor.styles[index] as any).code = style.code
input.script.code +=
'\n' +
`import '${createVuePartRequest(
filename,
'css',
'styles',
index
)}'`
if (style.module || descriptor.styles[index].scoped) {
return { ...style, code: '', map: undefined }
}
})
.filter(Boolean)
}
input.script.code = input.script.code.replace(/^\s+/gm, '')
const result = assemble(compiler, filename, beforeAssemble(input), opts)
descriptor.customBlocks.forEach((block, index) => {
if (!isAllowed(block.type)) return
result.code +=
'\n' +
`export * from '${createVuePartRequest(
filename,
(typeof block.attrs.lang === 'string' && block.attrs.lang) ||
createVuePartRequest.defaultLang[block.type] ||
block.type,
'customBlocks',
index
)}'`
})
dT(
`id: ${filename}\ncode:\n${result.code}\n\nmap:\n${JSON.stringify(
result.map,
null,
2
)}\n`
)
result.map = result.map || { mappings: '' }
return result
}
}
}
}
function createCustomBlockFilter(
customBlocks?: string[] | ((tag: string) => boolean)
): (tag: string) => boolean {
if (typeof customBlocks === 'function') return customBlocks
if (!Array.isArray(customBlocks)) return () => false
const allowed = new Set(customBlocks.filter(tag => !tag.startsWith('!')))
const notAllowed = new Set(
customBlocks.filter(tag => tag.startsWith('!')).map(tag => tag.substr(1))
)
return tag => {
if (allowed.has(tag)) return true
if (notAllowed.has(tag)) return false
if (notAllowed.has('*')) return false
return allowed.has('*')
}
}