Skip to content

Instantly share code, notes, and snippets.

@Baozi2
Last active March 12, 2018 09:38
Show Gist options
  • Save Baozi2/0aa48da3e1f64983fa979c8601f920db to your computer and use it in GitHub Desktop.
Save Baozi2/0aa48da3e1f64983fa979c8601f920db to your computer and use it in GitHub Desktop.
one webpack plugin create json file with template / 一个用于根据json模板文件生成json文件的webpack插件
"use strict"
const fs = require('fs');
const path = require('path');
function MP(templateFile, options){
let _this = this,
mp = {};
//获取webpack root
let rootPath = path.dirname(module.parent.filename);
let tmpFilePath = path.resolve(rootPath, templateFile);
mp.tmpFilePath = tmpFilePath;
if(fs.existsSync(templateFile)){
mp.existTMPFile = true;
}
if(typeof options === "string"){
//替换文件的路径
let settingFilePath = path.resolve(rootPath, options);
if(fs.existsSync(settingFilePath)){
mp.replaceFile = settingFilePath;
}else{
console.info('没有指定认识配置文件')
mp.data = null;
}
}else if(typeof options === 'object'){
mp.data = options;
}
if(!mp.existTMPFile && !mpMP.data){
throw '不能同时为空'
}
mp.temName = path.basename(tmpFilePath);
this.mp = mp;
}
MP.prototype.apply = function(compiler){
let _this = this,
originData = {},
destData = _this.mp.data,
webpackOptions = compiler.options,
output = webpackOptions.output.path;
compiler.plugin('emit', function(compilation, callback){
let watchedFiles = compilation.fileDependencies,
replaceFile = _this.mp.replaceFile;
if(_this.mp.existTMPFile){
originData = JSON.parse(fs.readFileSync(_this.mp.tmpFilePath));
}
if(replaceFile){
if(watchedFiles.includes(replaceFile)){
Object.assign(originData, readJSON(replaceFile));
}else{
Object.assign(originData, readJSON(replaceFile));
compilation.fileDependencies.push(replaceFile)
}
}else{
Object.assign(originData, destData);
}
compilation.assets[_this.mp.temName] = {
source: () => JSON.stringify(originData, null, 2),
size: () => originData.length,
};
callback();
})
}
function readJSON(file){
return JSON.parse(fs.readFileSync(file, 'utf8'))
}
module.exports = MP;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment