1
1
import webpack from 'webpack'
2
2
import { ParsedUrlQuery , parse } from 'querystring'
3
3
import { RawSourceMap } from 'source-map'
4
+ import JSON5 from 'json5'
5
+ import yaml from 'js-yaml'
4
6
5
7
const loader : webpack . loader . Loader = function (
6
8
source : string | Buffer , sourceMap : RawSourceMap | undefined ) : void {
@@ -20,14 +22,8 @@ const loader: webpack.loader.Loader = function (
20
22
}
21
23
22
24
function generateCode ( source : string | Buffer , query : ParsedUrlQuery ) : string {
23
- let code = ''
24
-
25
- let value = typeof source === 'string'
26
- ? JSON . parse ( source )
27
- : Buffer . isBuffer ( source )
28
- ? JSON . parse ( source . toString ( ) )
29
- : null
30
- if ( value === null ) { throw new Error ( 'invalid source!' ) }
25
+ const data = convert ( source , query . lang as string )
26
+ let value = JSON . parse ( data )
31
27
32
28
if ( query . locale && typeof query . locale === 'string' ) {
33
29
value = Object . assign ( { } , { [ query . locale ] : value } )
@@ -38,6 +34,7 @@ function generateCode (source: string | Buffer, query: ParsedUrlQuery): string {
38
34
. replace ( / \u2029 / g, '\\u2029' )
39
35
. replace ( / \\ / g, '\\\\' )
40
36
37
+ let code = ''
41
38
code += `function (Component) {
42
39
Component.options.__i18n = Component.options.__i18n || []
43
40
Component.options.__i18n.push('${ value . replace ( / \u0027 / g, '\\u0027' ) } ')
@@ -46,4 +43,19 @@ function generateCode (source: string | Buffer, query: ParsedUrlQuery): string {
46
43
return code
47
44
}
48
45
46
+ function convert ( source : string | Buffer , lang : string ) : string {
47
+ const value = Buffer . isBuffer ( source ) ? source . toString ( ) : source
48
+
49
+ switch ( lang ) {
50
+ case 'yaml' :
51
+ case 'yml' :
52
+ const data = yaml . safeLoad ( value )
53
+ return JSON . stringify ( data , undefined , '\t' )
54
+ case 'json5' :
55
+ return JSON . stringify ( JSON5 . parse ( value ) )
56
+ default :
57
+ return value
58
+ }
59
+ }
60
+
49
61
export default loader
0 commit comments