Created
February 14, 2017 15:30
-
-
Save UncleBill/e9ed7a5b11240b3d783f3d7fddfb15fc to your computer and use it in GitHub Desktop.
local-define-plugin, predefine for webpack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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