UNPKG

1.66 kBJavaScriptView Raw
1function ensureLoaderSuffix(name) {
2 const loaderSuffixRegexp = /-loader$/
3
4 return loaderSuffixRegexp.test(name) ? name : `${name}-loader`
5}
6
7
8
9class VueLoaderOptionPlugin {
10 constructor(options = {}) {
11 this.options = options
12 this.vueLoaderIdentifier = 'vue-loader/lib/selector'
13 }
14 apply(compiler) {
15 compiler.plugin('compilation', compilation => {
16 compilation.plugin('normal-module-loader', (context, module) => {
17 const loaderOption = this.matchLoaderOption(module.request, module.resource)
18
19 if (!loaderOption.loaderName || !loaderOption.options) {
20 return
21 }
22
23 module.loaders.forEach(l => {
24 if (l.loader.indexOf(loaderOption.loader) >= 0) {
25 if (loaderOption.options.toContext) {
26 context[loaderOption.loaderName] = loaderOption.options
27 } else {
28 l.options = loaderOption.options
29 }
30 }
31 })
32 })
33 })
34 }
35 matchLoaderOption(request, resource) {
36 const VUE_TEST = /\.vue$/
37 const i = resource.indexOf('?')
38
39 if (!VUE_TEST.test(i < 0 ? resource : resource.substr(0, i))) {
40 return {}
41 }
42
43
44 const loaders = request.split('!')
45
46 return loaders.reduceRight((ret, loader) => {
47 Object.keys(this.options).reduce((_, loaderName) => {
48 if (loader.indexOf(ensureLoaderSuffix(loaderName)) >= 0) {
49 ret = {
50 loaderName: loaderName,
51 loader: ensureLoaderSuffix(loaderName),
52 options: this.options[loaderName]
53 }
54 }
55 return {}
56 }, {})
57 return ret
58 }, {})
59 }
60}
61
62module.exports = VueLoaderOptionPlugin