Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.