1 | import webpack from 'webpack'
|
2 | import { ParsedUrlQuery, parse } from 'querystring'
|
3 | import { RawSourceMap } from 'source-map'
|
4 | import JSON5 from 'json5'
|
5 | import yaml from 'js-yaml'
|
6 |
|
7 | const loader: webpack.loader.Loader = function (
|
8 | source: string | Buffer, sourceMap: RawSourceMap | undefined): void {
|
9 | if (this.version && Number(this.version) >= 2) {
|
10 | try {
|
11 | this.cacheable && this.cacheable()
|
12 | this.callback(null, `module.exports = ${generateCode(source, parse(this.resourceQuery))}`, sourceMap)
|
13 | } catch (err) {
|
14 | this.emitError(err.message)
|
15 | this.callback(err)
|
16 | }
|
17 | } else {
|
18 | const message = 'support webpack 2 later'
|
19 | this.emitError(message)
|
20 | this.callback(new Error(message))
|
21 | }
|
22 | }
|
23 |
|
24 | function generateCode (source: string | Buffer, query: ParsedUrlQuery): string {
|
25 | const data = convert(source, query.lang as string)
|
26 | let value = JSON.parse(data)
|
27 |
|
28 | if (query.locale && typeof query.locale === 'string') {
|
29 | value = Object.assign({}, { [query.locale]: value })
|
30 | }
|
31 |
|
32 | value = JSON.stringify(value)
|
33 | .replace(/\u2028/g, '\\u2028')
|
34 | .replace(/\u2029/g, '\\u2029')
|
35 | .replace(/\\/g, '\\\\')
|
36 |
|
37 | let code = ''
|
38 | code += `function (Component) {
|
39 | Component.options.__i18n = Component.options.__i18n || []
|
40 | Component.options.__i18n.push('${value.replace(/\u0027/g, '\\u0027')}')
|
41 | delete Component.options._Ctor
|
42 | }\n`
|
43 | return code
|
44 | }
|
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 |
|
61 | export default loader
|