UNPKG

@monajs/env-config-webpack-plugin

Version:
102 lines (90 loc) 2.47 kB
/** * Generate configuration files based on env. * @author yangxi | 599321378@qq.com **/ const glob = require('glob') const fs = require('fs-extra') const path = require('path') const compose = require('koa-compose') const resolve = (filePath) => path.resolve(__dirname, filePath) const logTat = '[@monajs/env-config-webpack-plugin]: ' // dev | sit | pre | production const defaultEnv = 'production' class EnvConfigWebpackPlugin { constructor (options) { this.entry = options.entry if (!this.entry) throw new Error(`${logTat}The option \`entry\` is necessary.`) this.output = options.output if (!this.output) throw new Error(`${logTat}The option \`output\` is necessary.`) this.env = options.env || process.env.NODE_ENV || defaultEnv } // remove output files remove (ctx, next) { fs.remove(this.output, err => { if (err) throw err next() }) } // get path type, file or dir isDir (ctx, next) { fs.stat(this.entry, (err, stat) => { if (err) throw err const res = stat.isDirectory() ? 2 : (stat.isFile() ? 1 : 0) if (res === 0) { throw new Error(`${logTat}Please check if the path(\`${this.entry}\`) exists`) } this.isEntryDir = res === 2 next() }) } // ensure output path exists // generate json for output path action (ctx, next) { if (this.isEntryDir) { //dir fs.ensureDir(this.output, (err) => { if (err) throw err glob.sync(`${this.entry}/*.json`, { matchBase: true }).forEach((entry) => { const output = entry.replace(this.entry, this.output) this.generateJson(entry, output) }) }) } else { //file fs.ensureFile(this.output, (err) => { if (err) throw err this.generateJson(this.entry, this.output) }) } console.info(`${logTat}Generate configuration files success!`) next() } // generate json files generateJson (entry, ouput) { fs.readJson(entry, (err, json) => { if (err) throw err const data = Object.assign({}, json['common'], json[this.env]) fs.writeFile(ouput, JSON.stringify(data, null, '\t'), (err) => { if (err) throw err console.info(`${logTat} ${ouput}`) }) }) } end (ctx, next, callback) { callback() } apply (compiler) { // exec once compiler.plugin('run', (complication, callback) => { compose([ this.remove.bind(this), this.isDir.bind(this), this.action.bind(this), this.end.bind(this, callback) ])() }) } } module.exports = EnvConfigWebpackPlugin