1 | const path = require('path');
|
2 | const sourcer = require('sourcer');
|
3 | const webpack = require('webpack');
|
4 | const webpackMerge = require('webpack-merge');
|
5 | const webpackUtils = require('./webpackUtils');
|
6 | const utils = require('../utils');
|
7 |
|
8 | module.exports = class webpackBuilder {
|
9 | constructor(source, dest, options = {}) {
|
10 | const root = options.root || process.cwd();
|
11 | if (typeof source === "object" && typeof source.length === "undefined") {
|
12 | this.sourceDef = ".vue";
|
13 | this.source = source;
|
14 | this.base = options.base || '';
|
15 | } else {
|
16 | const ext = path.extname(source);
|
17 | this.sourceDef = source;
|
18 | if (ext) {
|
19 | this.source = [path.resolve(source)];
|
20 | this.base = options.base || sourcer.base(source);
|
21 | } else {
|
22 | this.source = sourcer.find(root, source, {
|
23 | recursive: true
|
24 | });
|
25 | this.base = sourcer.base(source);
|
26 | if (options.ext) {
|
27 | const reg = new RegExp('\\.(' + options.ext + ')$');
|
28 | this.source = this.source.filter(s => reg.test(path.extname(s)));
|
29 | }
|
30 | }
|
31 | }
|
32 | if (!utils.isJson(options.babelOptions)) {
|
33 | options.babelOptions = {};
|
34 | }
|
35 | this.dest = path.resolve(dest);
|
36 | this.options = options;
|
37 | }
|
38 |
|
39 | build(callback) {
|
40 | this.mergeConfig = {};
|
41 | if (this.source.length === 0) {
|
42 | return callback('no ' + (this.options.ext || '') + ' files found in source "' + this.sourceDef + '"');
|
43 | }
|
44 | if (this.options.config && webpackUtils.accessSync(this.options.config)) {
|
45 | this.mergeConfig = require(path.resolve(this.options.config));
|
46 | }
|
47 | this.webpackCompiler = webpack(webpackMerge(this.config, this.mergeConfig));
|
48 | this.webpackFormatResult = (err, stats) => {
|
49 | const result = {
|
50 | toString: () => stats.toString({
|
51 | warnings: false,
|
52 | version: false,
|
53 | hash: false,
|
54 | assets: true,
|
55 | modules: false,
|
56 | chunkModules: false,
|
57 | chunkOrigins: false,
|
58 | entrypoints: false,
|
59 | children: false,
|
60 | chunks: false,
|
61 | colors: true
|
62 | })
|
63 | };
|
64 | if (err) {
|
65 | console.error(err.stack || err);
|
66 | if (err.details) {
|
67 | console.error(err.details);
|
68 | }
|
69 | return callback && callback(err);
|
70 | }
|
71 |
|
72 | const info = stats.toJson();
|
73 | if (stats.hasErrors()) {
|
74 | return callback && callback(info.errors, result, info);
|
75 | }
|
76 | callback && callback(err, result, info);
|
77 | };
|
78 | if (this.config.watch) {
|
79 | this.webpackWatching = this.webpackCompiler.watch({
|
80 | aggregateTimeout: 300,
|
81 | ignored: /node_modules/,
|
82 | poll: false,
|
83 | }, this.webpackFormatResult);
|
84 | } else {
|
85 | this.webpackCompiler.run(this.webpackFormatResult);
|
86 | }
|
87 | return this;
|
88 | }
|
89 | };
|