1 | const path = require('path');
|
2 | const fs = require('fs-extra');
|
3 | const _ = require('lodash');
|
4 | const chalk = require('chalk');
|
5 |
|
6 | function 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 |
|
33 | nuxt.rootDir = nuxt.rootDir || path.resolve('');
|
34 | nuxt.srcDir = nuxt.srcDir || nuxt.rootDir;
|
35 |
|
36 |
|
37 | nuxt.nuxtHelpersDir = path.resolve(nuxt.rootDir, '.nuxt-helpers');
|
38 | fs.mkdirsSync(nuxt.nuxtHelpersDir);
|
39 |
|
40 |
|
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 |
|
52 | nuxt.plugins = _.uniq(nuxt.plugins);
|
53 | nuxt.build.vendor = _.uniq(nuxt.build.vendor);
|
54 |
|
55 | return nuxt;
|
56 | }
|
57 |
|
58 | function install(helperName, nuxt) {
|
59 | const modulePath = path.resolve(__dirname, helperName);
|
60 | let helper;
|
61 | const warns = [];
|
62 |
|
63 | try {
|
64 |
|
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 |
|
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 |
|
89 | let plugin = helper.plugin;
|
90 | if (plugin instanceof Function) {
|
91 | plugin = plugin(nuxt);
|
92 | }
|
93 |
|
94 | if (plugin) {
|
95 |
|
96 | if (plugin === true) {
|
97 | plugin = path.resolve(modulePath, 'plugin.js');
|
98 | }
|
99 |
|
100 |
|
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 |
|
127 | module.exports = wrap;
|