UNPKG

2.45 kBJavaScriptView Raw
1'use strict';
2
3require('path');
4var fs = require('fs');
5require('globby');
6require('lodash');
7var scan = require('./scan-ac69cc50.js');
8var loaderUtils = require('loader-utils');
9var vueTemplateCompiler = require('vue-template-compiler');
10
11function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
12
13var loaderUtils__default = /*#__PURE__*/_interopDefaultLegacy(loaderUtils);
14
15async function extractTags(resourcePath) {
16 const tags = new Set();
17 const file = (await fs.readFileSync(resourcePath)).toString('utf8');
18 const component = vueTemplateCompiler.parseComponent(file);
19
20 if (component.template) {
21 if (component.template.lang === 'pug') {
22 try {
23 const pug = require('pug');
24
25 component.template.content = pug.render(component.template.content, {
26 filename: resourcePath
27 });
28 } catch (err) {
29 /* Ignore compilation errors, they'll be picked up by other loaders */
30 }
31 }
32
33 vueTemplateCompiler.compile(component.template.content, {
34 modules: [{
35 postTransformNode: el => {
36 tags.add(el.tag);
37 }
38 }]
39 });
40 }
41
42 return [...tags];
43}
44
45function install(content, components) {
46 const imports = '{' + components.map(c => `${c.pascalName}: ${c.import}`).join(',') + '}';
47 let newContent = '/* nuxt-component-imports */\n';
48 newContent += `installComponents(component, ${imports})\n`; // Insert our modification before the HMR code
49
50 const hotReload = content.indexOf('/* hot reload */');
51
52 if (hotReload > -1) {
53 content = content.slice(0, hotReload) + newContent + '\n\n' + content.slice(hotReload);
54 } else {
55 content += '\n\n' + newContent;
56 }
57
58 return content;
59}
60
61async function loader(content) {
62 this.async();
63 this.cacheable();
64
65 if (!this.resourceQuery) {
66 this.addDependency(this.resourcePath);
67 const {
68 dependencies,
69 getComponents
70 } = {
71 dependencies: [],
72 getComponents: () => [],
73 ...loaderUtils__default['default'].getOptions(this)
74 };
75
76 for (const dependency of dependencies) {
77 this.addDependency(dependency);
78 }
79
80 const tags = await extractTags(this.resourcePath);
81 const matchedComponents = scan.matcher(tags, getComponents());
82
83 if (matchedComponents.length) {
84 content = install.call(this, content, matchedComponents);
85 }
86 }
87
88 this.callback(null, content);
89}
90
91module.exports = loader;