/ lib / modules / pipeline / webpackConfigReader.js
webpackConfigReader.js
 1  
 2  const {errorMessage} = require('../../utils/utils');
 3  const fs = require('../../core/fs');
 4  
 5  class WebpackConfigReader {
 6    constructor(options) {
 7      this.webpackConfigName = options.webpackConfigName;
 8    }
 9  
10    async readConfig(callback){
11      const dappConfigPath = fs.dappPath('webpack.config.js');
12      const defaultConfigPath = fs.embarkPath('lib/modules/pipeline', 'webpack.config.js');
13  
14      let config, configPath;
15      try {
16        if (fs.existsSync(dappConfigPath)) {
17          configPath = dappConfigPath;
18          delete require.cache[configPath];
19        } else {
20          configPath = defaultConfigPath;
21        }
22        config = require(configPath);
23        // valid config types: https://webpack.js.org/configuration/configuration-types/
24        // + function that returns a config object
25        // + function that returns a promise for a config object
26        // + array of named config objects
27        // + config object
28        if (typeof config === 'function') {
29          config = await config(this.webpackConfigName);
30        } else if (Array.isArray(config)) {
31          config = config.filter(cfg => cfg.name === this.webpackConfigName);
32          if (!config.length) {
33            return callback(`no webpack config has the name '${this.webpackConfigName}'`);
34          }
35          if (config.length > 1) {
36            console.warn(`detected ${config.length} webpack configs having the name '${this.webpackConfigName}', using the first one`);
37          }
38          config = config[0];
39        }
40        callback(null, config);
41      } catch (e) {
42        console.error(`error while loading webpack config ${configPath}`);
43        callback(errorMessage(e));
44      }    
45    }
46  }
47  
48  module.exports = WebpackConfigReader;