Skip to content

Instantly share code, notes, and snippets.

@UncleBill
Created February 14, 2017 15:30
Show Gist options
  • Save UncleBill/e9ed7a5b11240b3d783f3d7fddfb15fc to your computer and use it in GitHub Desktop.
Save UncleBill/e9ed7a5b11240b3d783f3d7fddfb15fc to your computer and use it in GitHub Desktop.
local-define-plugin, predefine for webpack
var RawSource = require('webpack-core/lib/RawSource')
function TestPlugin (options) {
}
var jsrg = /\.js($|\?)/i;
TestPlugin.prototype.apply = function (compiler) {
debugger;
compiler.plugin('compilation', function (compilation) {
debugger;
compilation.plugin('optimize-chunk-assets', function (chunks) {
chunks.forEach(function (chunk) {
var files = [];
chunk.files.forEach(function (file) {
files.push(file)
})
files = files.filter(file => jsrg.test(file));
console.log(files);
files.forEach(file => {
try {
const asset = compilation.assets[file];
const source = asset.source();
const result = compileDefine(source);
compilation.assets[file] = new RawSource(result);
} catch (e) {
compilation.errors.push(e);
}
})
})
var raws = new RawSource(compilation.assets['bundle.js'])
debugger;
})
})
compiler.plugin('emit', function (compilation, callback) {
debugger;
callback();
})
}
function compileDefine(src) {
// console.log('compile ', src);
var defs = src.match(/define\s*=\s*({.*})/);
// console.log('defs', defs);
if (!defs) {
return src;
}
var defobj = {};
eval('defobj=' + defs[1]);
var keys = Object.keys(defobj);
console.log('defobj', defobj, 'keys', keys);
keys.forEach(varkey => {
var re = new RegExp('\\b'+varkey+'\\b', 'g')
console.log(re);
src = src.replace(re, defobj[varkey]);
})
console.log(src);
return src;
}
module.exports = TestPlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment