/
index.ts
825 lines (747 loc) · 24.4 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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
import { createUnplugin, TransformResult } from 'unplugin'
import { normalize, parse as parsePath } from 'pathe'
import createDebug from 'debug'
import fg from 'fast-glob'
import {
isArray,
isObject,
isEmptyObject,
isString,
isNumber,
isBoolean,
assign,
generateCodeFrame
} from '@intlify/shared'
import { createFilter } from '@rollup/pluginutils'
import {
generateJSON,
generateYAML,
generateJavaScript,
checkInstallPackage,
checkVueI18nBridgeInstallPackage,
getVueI18nVersion
} from '@intlify/bundle-utils'
import { RawSourceMap } from 'source-map'
import { parse } from '@vue/compiler-sfc'
import { parseVueRequest, VueQuery } from './query'
import { createBridgeCodeGenerator } from './legacy'
import { getRaw, warn, error, raiseError } from './utils'
import type {
UnpluginContextMeta,
UnpluginOptions,
SourceMapCompact
} from 'unplugin'
import type { SourceMapInput } from 'rollup'
import type { PluginOptions } from './types'
import type { CodeGenOptions, DevEnv } from '@intlify/bundle-utils'
const INTLIFY_BUNDLE_IMPORT_ID = '@intlify/unplugin-vue-i18n/messages'
const INTLIFY_BUNDLE_IMPORT_DEPRECTED_ID =
'@intlify/vite-plugin-vue-i18n/messages'
const VIRTUAL_PREFIX = '\0'
const debug = createDebug('unplugin-vue-i18n')
const installedPkg = checkInstallPackage('@intlify/unplugin-vue-i18n', debug)
const installedVueI18nBridge = checkVueI18nBridgeInstallPackage(debug)
const vueI18nVersion = getVueI18nVersion(debug)
export const unplugin = createUnplugin<PluginOptions>((options = {}, meta) => {
debug('plugin options:', options, meta.framework)
// check bundler type
if (!['vite', 'webpack'].includes(meta.framework)) {
raiseError(`This plugin is supported 'vite' and 'webpack' only`)
}
// normalize for `options.include`
let include = options.include
let exclude = null
if (include) {
if (isArray(include)) {
include = include.map(item => normalize(item))
} else if (isString(include)) {
include = normalize(include)
}
} else {
exclude = '**/**'
}
const filter = createFilter(include, exclude)
const forceStringify = !!options.forceStringify
const defaultSFCLang = isString(options.defaultSFCLang)
? options.defaultSFCLang
: 'json'
const globalSFCScope = !!options.globalSFCScope
const useClassComponent = !!options.useClassComponent
const bridge = !!options.bridge
debug('bridge', bridge)
const runtimeOnly = isBoolean(options.runtimeOnly)
? options.runtimeOnly
: true
debug('runtimeOnly', runtimeOnly)
// prettier-ignore
const compositionOnly = installedPkg === 'vue-i18n'
? isBoolean(options.compositionOnly)
? options.compositionOnly
: true
: true
debug('compositionOnly', compositionOnly)
// prettier-ignore
const fullInstall = installedPkg === 'vue-i18n'
? isBoolean(options.fullInstall)
? options.fullInstall
: true
: false
debug('fullInstall', fullInstall)
const useVueI18nImportName = options.useVueI18nImportName
if (useVueI18nImportName != null) {
warn(`'useVueI18nImportName' option is experimental`)
}
debug('useVueI18nImportName', useVueI18nImportName)
// prettier-ignore
const getVueI18nAliasName = () =>
vueI18nVersion === '9' || vueI18nVersion === '8'
? 'vue-i18n'
: vueI18nVersion === 'unknown' && installedPkg === 'petite-vue-i18n' && isBoolean(useVueI18nImportName) && useVueI18nImportName
? 'vue-i18n'
: installedPkg
const getVueI18nBridgeAliasPath = () =>
`vue-i18n-bridge/dist/vue-i18n-bridge.runtime.esm-bundler.js`
const getVueI18nAliasPath = (aliasName: string) =>
vueI18nVersion === '8'
? `${aliasName}/dist/${aliasName}.esm.js` // for vue-i18n@8
: `${aliasName}/dist/${installedPkg}.runtime.esm-bundler.js`
const esm = isBoolean(options.esm) ? options.esm : true
debug('esm', esm)
let isProduction = false
let sourceMap = false
const vueI18nAliasName = getVueI18nAliasName()
return {
name: 'unplugin-vue-i18n',
/**
* NOTE:
*
* For vite, If we have json (including SFC's custom block),
* transform it first because it will be transformed into javascript code by `vite:json` plugin.
*
* For webpack, This plugin will handle with ‘post’, because vue-loader generate the request query.
*/
enforce: meta.framework === 'vite' ? 'pre' : 'post',
vite: {
config(config, { command }) {
config.resolve = normalizeConfigResolveAlias(
config.resolve,
meta.framework
)
if (command === 'build' && runtimeOnly) {
debug(`vue-i18n alias name: ${vueI18nAliasName}`)
if (isArray(config.resolve!.alias)) {
config.resolve!.alias.push({
find: vueI18nAliasName,
replacement: getVueI18nAliasPath(vueI18nAliasName)
})
if (installedVueI18nBridge) {
config.resolve!.alias.push({
find: 'vue-i18n-bridge',
replacement: getVueI18nBridgeAliasPath()
})
}
} else if (isObject(config.resolve!.alias)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(config.resolve!.alias as any)[vueI18nAliasName] =
getVueI18nAliasPath(vueI18nAliasName)
if (installedVueI18nBridge) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(config.resolve!.alias as any)['vue-i18n-bridge'] =
getVueI18nBridgeAliasPath()
}
}
debug(
`set ${vueI18nAliasName} runtime only: ${getVueI18nAliasPath(
vueI18nAliasName
)}`
)
if (installedVueI18nBridge) {
debug(
`set vue-i18n-bridge runtime only: ${getVueI18nBridgeAliasPath()}`
)
}
} else if (
command === 'serve' &&
installedPkg === 'petite-vue-i18n' &&
useVueI18nImportName
) {
config.resolve = normalizeConfigResolveAlias(
config.resolve,
meta.framework
)
if (isArray(config.resolve!.alias)) {
config.resolve!.alias.push({
find: vueI18nAliasName,
replacement: `petite-vue-i18n/dist/petite-vue-i18n.esm-bundler.js`
})
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(config.resolve!.alias as any)[
vueI18nAliasName
] = `petite-vue-i18n/dist/petite-vue-i18n.esm-bundler.js`
}
debug(`petite-vue-i18n alias name: ${vueI18nAliasName}`)
}
config.define = config.define || {}
config.define['__VUE_I18N_LEGACY_API__'] = !compositionOnly
debug(
`set __VUE_I18N_LEGACY_API__ is '${config.define['__VUE_I18N_LEGACY_API__']}'`
)
config.define['__VUE_I18N_FULL_INSTALL__'] = fullInstall
debug(
`set __VUE_I18N_FULL_INSTALL__ is '${config.define['__VUE_I18N_FULL_INSTALL__']}'`
)
config.define['__VUE_I18N_PROD_DEVTOOLS__'] = false
},
configResolved(config) {
isProduction = config.isProduction
sourceMap =
config.command === 'build' ? !!config.build.sourcemap : false
debug(
`configResolved: isProduction = ${isProduction}, sourceMap = ${sourceMap}`
)
// json transform handling
const jsonPlugin = config.plugins.find(p => p.name === 'vite:json')
if (jsonPlugin) {
const orgTransform = jsonPlugin.transform // backup @rollup/plugin-json
jsonPlugin.transform = async function (code: string, id: string) {
if (!/\.json$/.test(id) || filter(id)) {
return
}
/**
* NOTE:
* `vite:json` plugin will be handled if the query generated from the result of parse SFC
* with `vite:vue` plugin contains json as follows.
* e.g src/components/HelloI18n.vue?vue&type=i18n&index=1&lang.json
*
* To avoid this, return the result that has already been processed (`enforce: 'pre'`) in the wrapped json plugin.
*/
const { query } = parseVueRequest(id)
if (query.vue) {
return
}
debug('org json plugin')
return orgTransform!.apply(this, [code, id])
}
}
/**
* typescript transform handling
*
* NOTE:
* Typescript resources are handled using the already existing `vite:esbuild` plugin.
*/
const esbuildPlugin = config.plugins.find(
p => p.name === 'vite:esbuild'
)
if (esbuildPlugin) {
const orgTransform = esbuildPlugin.transform // backup @rollup/plugin-json
// @ts-ignore
esbuildPlugin.transform = async function (code: string, id: string) {
const result = (await orgTransform!.apply(this, [
code,
id
])) as TransformResult
if (result == null) {
return result
}
const { filename, query } = parseVueRequest(id)
if (!query.vue && filter(id) && /\.[c|m]?ts$/.test(id)) {
const [_code, inSourceMap]: [string, RawSourceMap | undefined] =
isString(result)
? [result, undefined]
: [result.code, result.map as RawSourceMap]
let langInfo = defaultSFCLang
langInfo = parsePath(filename)
.ext as Required<PluginOptions>['defaultSFCLang']
const generate = getGenerator(langInfo)
const parseOptions = getOptions(
filename,
isProduction,
query as Record<string, unknown>,
sourceMap,
{
inSourceMap,
isGlobal: globalSFCScope,
useClassComponent,
bridge,
exportESM: esm,
forceStringify
}
) as CodeGenOptions
debug('parseOptions', parseOptions)
const { code: generatedCode, map } = generate(
_code,
parseOptions,
bridge ? createBridgeCodeGenerator(_code, query) : undefined
)
debug('generated code', generatedCode)
debug('sourcemap', map, sourceMap)
if (_code === generatedCode) return
return {
code: generatedCode,
map: (sourceMap ? map : { mappings: '' }) as any // eslint-disable-line @typescript-eslint/no-explicit-any
}
} else {
return result
}
}
}
},
async handleHotUpdate({ file, server }) {
if (/\.(json5?|ya?ml)$/.test(file)) {
const module = server.moduleGraph.getModuleById(
asVirtualId(INTLIFY_BUNDLE_IMPORT_ID, meta.framework)
)
if (module) {
server.moduleGraph.invalidateModule(module)
return [module!]
}
}
}
},
webpack(compiler) {
isProduction = compiler.options.mode !== 'development'
sourceMap = !!compiler.options.devtool
debug(`webpack: isProduction = ${isProduction}, sourceMap = ${sourceMap}`)
compiler.options.resolve = normalizeConfigResolveAlias(
compiler.options.resolve,
meta.framework
)
if (isProduction && runtimeOnly) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(compiler.options.resolve!.alias as any)[vueI18nAliasName] =
getVueI18nAliasPath(vueI18nAliasName)
if (installedVueI18nBridge) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(compiler.options.resolve!.alias as any)['vue-i18n-bridge'] =
getVueI18nBridgeAliasPath()
}
debug(
`set ${vueI18nAliasName} runtime only: ${getVueI18nAliasPath(
vueI18nAliasName
)}`
)
if (installedVueI18nBridge) {
debug(
`set vue-i18n-bridge runtime only: ${getVueI18nBridgeAliasPath()}`
)
}
} else if (
!isProduction &&
installedPkg === 'petite-vue-i18n' &&
useVueI18nImportName
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(compiler.options.resolve!.alias as any)[
vueI18nAliasName
] = `petite-vue-i18n/dist/petite-vue-i18n.esm-bundler.js`
debug(`petite-vue-i18n alias name: ${vueI18nAliasName}`)
}
loadWebpack().then(webpack => {
if (webpack) {
compiler.options.plugins!.push(
new webpack.DefinePlugin({
__VUE_I18N_LEGACY_API__: JSON.stringify(compositionOnly),
__VUE_I18N_FULL_INSTALL__: JSON.stringify(fullInstall),
__INTLIFY_PROD_DEVTOOLS__: 'false'
})
)
debug(`set __VUE_I18N_LEGACY_API__ is '${compositionOnly}'`)
debug(`set __VUE_I18N_FULL_INSTALL__ is '${fullInstall}'`)
} else {
debug('ignore vue-i18n feature flags with webpack.DefinePlugin')
}
})
/**
* NOTE:
* After i18n resources are transformed into javascript by transform, avoid further transforming by webpack.
*/
if (compiler.options.module) {
compiler.options.module.rules.push({
test: /\.(json5?|ya?ml)$/,
type: 'javascript/auto',
include(resource: string) {
return filter(resource)
}
})
}
// TODO:
// HMR for webpack
},
resolveId(id: string, importer: string) {
debug('resolveId', id, importer)
if (id === INTLIFY_BUNDLE_IMPORT_DEPRECTED_ID) {
warn(
`deprected '${INTLIFY_BUNDLE_IMPORT_DEPRECTED_ID}', you should switch to '${INTLIFY_BUNDLE_IMPORT_ID}'`
)
return asVirtualId(id, meta.framework)
}
if (id === INTLIFY_BUNDLE_IMPORT_ID) {
return asVirtualId(id, meta.framework)
}
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async load(id: string) {
debug('load', id)
const { query } = parseVueRequest(id)
if (
[INTLIFY_BUNDLE_IMPORT_DEPRECTED_ID, INTLIFY_BUNDLE_IMPORT_ID].includes(
getVirtualId(id, meta.framework)
) &&
include
) {
let resourcePaths = [] as string[]
const includePaths = isArray(include) ? include : [include]
for (const inc of includePaths) {
resourcePaths = [...resourcePaths, ...(await fg(inc))]
}
resourcePaths = resourcePaths.filter(
(el, pos) => resourcePaths.indexOf(el) === pos
)
const code = await generateBundleResources(
resourcePaths,
query,
isProduction,
{
forceStringify,
bridge,
exportESM: esm,
useClassComponent
}
)
// TODO: support virtual import identifier
// for virtual import identifier (@intlify/unplugin-vue-i18n/messages)
return {
code,
map: { mappings: '' }
}
}
},
transformInclude(id) {
debug('transformInclude', id)
if (meta.framework === 'vite') {
return true
} else {
const { filename } = parseVueRequest(id)
return (
filename.endsWith('vue') ||
filename.endsWith(INTLIFY_BUNDLE_IMPORT_ID) ||
filename.endsWith(INTLIFY_BUNDLE_IMPORT_DEPRECTED_ID) ||
(/\.(json5?|ya?ml)$/.test(filename) && filter(filename))
)
}
},
async transform(code, id) {
const { filename, query } = parseVueRequest(id)
debug('transform', id, JSON.stringify(query), filename)
let langInfo = defaultSFCLang
let inSourceMap: RawSourceMap | undefined
if (!query.vue) {
if (/\.(json5?|ya?ml|[c|m]?js)$/.test(id) && filter(id)) {
langInfo = parsePath(filename)
.ext as Required<PluginOptions>['defaultSFCLang']
const generate = getGenerator(langInfo)
const parseOptions = getOptions(
filename,
isProduction,
query as Record<string, unknown>,
sourceMap,
{
inSourceMap,
isGlobal: globalSFCScope,
useClassComponent,
bridge,
exportESM: esm,
forceStringify
}
) as CodeGenOptions
debug('parseOptions', parseOptions)
const { code: generatedCode, map } = generate(
code,
parseOptions,
bridge ? createBridgeCodeGenerator(code, query) : undefined
)
debug('generated code', generatedCode)
debug('sourcemap', map, sourceMap)
if (code === generatedCode) return
return {
code: generatedCode,
map: (sourceMap ? map : { mappings: '' }) as any // eslint-disable-line @typescript-eslint/no-explicit-any
}
} else {
// TODO: support virtual import identifier
// for virtual import identifier (@intlify/unplugin-vue-i18n/messages)
}
} else {
// for Vue SFC
if (isCustomBlock(query)) {
if (isString(query.lang)) {
langInfo = (
query.src
? query.lang === 'i18n'
? 'json'
: query.lang
: query.lang
) as Required<PluginOptions>['defaultSFCLang']
} else if (defaultSFCLang) {
langInfo = defaultSFCLang
}
debug('langInfo', langInfo)
const generate = /\.?json5?/.test(langInfo)
? generateJSON
: generateYAML
const parseOptions = getOptions(
filename,
isProduction,
query as Record<string, unknown>,
sourceMap,
{
inSourceMap,
isGlobal: globalSFCScope,
useClassComponent,
bridge,
exportESM: esm,
forceStringify
}
) as CodeGenOptions
debug('parseOptions', parseOptions)
const source = await getCode(
code,
filename,
sourceMap,
query,
meta.framework
)
const { code: generatedCode, map } = generate(
source,
parseOptions,
bridge ? createBridgeCodeGenerator(source, query) : undefined
)
debug('generated code', generatedCode)
debug('sourcemap', map, sourceMap)
if (code === generatedCode) return
return {
code: generatedCode,
map: (sourceMap ? map : { mappings: '' }) as any // eslint-disable-line @typescript-eslint/no-explicit-any
}
}
}
}
} as UnpluginOptions
})
function getGenerator(ext: string, defaultGen = generateJSON) {
// prettier-ignore
return /\.?json5?$/.test(ext)
? generateJSON
: /\.ya?ml$/.test(ext)
? generateYAML
: /\.([c|m]?js|[c|m]?ts)$/.test(ext)
? generateJavaScript
: defaultGen
}
function normalizeConfigResolveAlias(
resolve: any, // eslint-disable-line @typescript-eslint/no-explicit-any
framework: UnpluginContextMeta['framework']
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): any {
if (resolve && resolve.alias) {
return resolve
}
if (!resolve) {
if (framework === 'vite') {
return { alias: [] }
} else if (framework === 'webpack') {
return { alias: {} }
}
} else if (!resolve.alias) {
if (framework === 'vite') {
resolve.alias = []
return resolve
} else if (framework === 'webpack') {
resolve.alias = {}
return resolve
}
}
}
async function loadWebpack() {
let webpack = null
try {
webpack = await import('webpack').then(m => m.default || m)
} catch (e) {
warn(`webpack not found, please install webpack.`)
}
return webpack
}
async function generateBundleResources(
resources: string[],
query: VueQuery,
isProduction: boolean,
{
forceStringify = false,
isGlobal = false,
bridge = false,
exportESM = true,
useClassComponent = false
}: {
forceStringify?: boolean
isGlobal?: boolean
bridge?: boolean
exportESM?: boolean
useClassComponent?: boolean
}
) {
const codes = []
for (const res of resources) {
debug(`${res} bundle loading ...`)
if (/\.(json5?|ya?ml)$/.test(res)) {
const { ext, name } = parsePath(res)
const source = await getRaw(res)
const generate = /json5?/.test(ext) ? generateJSON : generateYAML
const parseOptions = getOptions(res, isProduction, {}, false, {
isGlobal,
useClassComponent,
bridge,
exportESM,
forceStringify
}) as CodeGenOptions
parseOptions.type = 'bare'
const { code } = generate(
source,
parseOptions,
bridge ? createBridgeCodeGenerator(source, query) : undefined
)
debug('generated code', code)
codes.push(`${JSON.stringify(name)}: ${code}`)
}
}
return `export default {
${codes.join(`,\n`)}
}`
}
async function getCode(
source: string,
filename: string,
sourceMap: boolean,
query: VueQuery,
framework: UnpluginContextMeta['framework'] = 'vite'
): Promise<string> {
const { index, issuerPath } = query
if (!isNumber(index)) {
raiseError(`unexpected index: ${index}`)
}
if (framework === 'webpack') {
if (issuerPath) {
// via `src=xxx` of SFC
debug(`getCode (webpack) ${index} via issuerPath`, issuerPath)
return await getRaw(filename)
} else {
const result = parse(await getRaw(filename), {
sourceMap,
filename
})
const block = result.descriptor.customBlocks[index!]
if (block) {
const code = block.src ? await getRaw(block.src) : block.content
debug(`getCode (webpack) ${index} from SFC`, code)
return code
} else {
return source
}
}
} else {
return source
}
}
function isCustomBlock(query: VueQuery): boolean {
return (
!isEmptyObject(query) &&
'vue' in query &&
(query['type'] === 'custom' || // for vite (@vite-plugin-vue)
query['type'] === 'i18n' || // for webpack (vue-loader)
query['blockType'] === 'i18n') // for webpack (vue-loader)
)
}
function getOptions(
filename: string,
isProduction: boolean,
query: VueQuery,
sourceMap: boolean,
{
inSourceMap = undefined,
forceStringify = false,
isGlobal = false,
bridge = false,
exportESM = true,
useClassComponent = false
}: {
inSourceMap?: RawSourceMap
forceStringify?: boolean
isGlobal?: boolean
bridge?: boolean
exportESM?: boolean
useClassComponent?: boolean
}
): Record<string, unknown> {
const mode: DevEnv = isProduction ? 'production' : 'development'
const baseOptions = {
filename,
sourceMap,
inSourceMap,
forceStringify,
useClassComponent,
bridge,
exportESM,
env: mode,
onWarn: (msg: string): void => {
warn(`${filename} ${msg}`)
},
onError: (
msg: string,
extra?: NonNullable<Parameters<NonNullable<CodeGenOptions['onError']>>>[1]
): void => {
const codeFrame = generateCodeFrame(
extra?.source || extra?.location?.source || '',
extra?.location?.start.column,
extra?.location?.end.column
)
const errMssage = `${msg} (error code: ${extra?.code}) in ${filename}
target message: ${extra?.source}
target message path: ${extra?.path}
${codeFrame}
`
error(errMssage)
throw new Error(errMssage)
}
}
if (isCustomBlock(query)) {
return assign(baseOptions, {
type: 'sfc',
locale: isString(query.locale) ? query.locale : '',
isGlobal: isGlobal || !!query.global
})
} else {
return assign(baseOptions, {
type: 'plain',
isGlobal: false
})
}
}
function getVirtualId(
id: string,
framework: UnpluginContextMeta['framework'] = 'vite'
) {
// prettier-ignore
return framework === 'vite'
? id.startsWith(VIRTUAL_PREFIX)
? id.slice(VIRTUAL_PREFIX.length)
: ''
: id
}
function asVirtualId(
id: string,
framework: UnpluginContextMeta['framework'] = 'vite'
) {
return framework === 'vite' ? VIRTUAL_PREFIX + id : id
}
export default unplugin
export * from './types'