UNPKG

3.09 kBJavaScriptView Raw
1const path = require('path');
2const fs = require('fs-extra');
3const _ = require('lodash');
4const chalk = require('chalk');
5
6function wrap(helpers, nuxt) {
7 if (!nuxt) {
8 return;
9 }
10
11 if (!Array.isArray(helpers)) {
12 helpers = [helpers];
13 }
14
15 _.defaultsDeep(nuxt, {
16 build: {
17 postcss: [],
18 vendor: [],
19 plugins: []
20 },
21 css: [],
22 plugins: [],
23 head: {
24 meta: [],
25 link: [],
26 style: [],
27 script: []
28 },
29 env: {}
30 });
31
32 // Explicit rootDir and srcDir
33 nuxt.rootDir = nuxt.rootDir || path.resolve('');
34 nuxt.srcDir = nuxt.srcDir || nuxt.rootDir;
35
36 // Cleanup & ensure .nuxt-helpers dir exits
37 nuxt.nuxtHelpersDir = path.resolve(nuxt.rootDir, '.nuxt-helpers');
38 fs.mkdirsSync(nuxt.nuxtHelpersDir);
39
40 // Install helpers
41 helpers.forEach(m => {
42 const warns = install(m, nuxt);
43 if (warns.length > 0) {
44 console.log(chalk.yellow(`[Nuxt Helpers] ${m}:`));
45 warns.forEach(warn => {
46 console.log(` - ${chalk.yellow(warn)}`);
47 });
48 }
49 });
50
51 // Ensure uniques after helpers install
52 nuxt.plugins = _.uniq(nuxt.plugins);
53 nuxt.build.vendor = _.uniq(nuxt.build.vendor);
54
55 return nuxt;
56}
57
58function install(helperName, nuxt) {
59 const modulePath = path.resolve(__dirname, helperName);
60 let helper;
61 const warns = [];
62
63 try {
64 /* eslint-disable import/no-dynamic-require */
65 helper = require(modulePath);
66 } catch (err) {
67 console.error(err);
68 }
69
70 if (!helper) {
71 warns.push('Cannot load helper', helperName);
72 return warns;
73 }
74
75 if (helper.vendor) {
76 nuxt.build.vendor = nuxt.build.vendor.concat(helper.vendor);
77
78 // Check helper vendors to be installed
79 helper.vendor.forEach(vendor => {
80 try {
81 require(vendor);
82 } catch (err) {
83 warns.push('Dependency not installed: ' + chalk.blue(vendor));
84 }
85 });
86 }
87
88 // Dynamic plugins
89 let plugin = helper.plugin;
90 if (plugin instanceof Function) {
91 plugin = plugin(nuxt);
92 }
93
94 if (plugin) {
95 // Resolve plugin path
96 if (plugin === true) {
97 plugin = path.resolve(modulePath, 'plugin.js');
98 }
99
100 // Copy plugin to project
101 const filename = helperName + '.js';
102 const dst = path.resolve(nuxt.nuxtHelpersDir, filename);
103 fs.copySync(plugin, dst);
104
105 if (helper.copyOnly !== false) {
106 nuxt.plugins.push({src: dst, ssr: (helper.ssr !== false)});
107 }
108 }
109
110 if (helper.extend) {
111 helper.extend(nuxt);
112 }
113
114 if (helper.extendBuild) {
115 const _extend = nuxt.build.extend;
116 nuxt.build.extend = function () {
117 helper.extendBuild.apply(this, arguments);
118 if (_extend) {
119 _extend.apply(this, arguments);
120 }
121 };
122 }
123
124 return warns;
125}
126
127module.exports = wrap;