|
| 1 | +/* |
| 2 | + * Copyright (c) 2018 Coremail.cn, Ltd. All Rights Reserved. |
| 3 | + */ |
| 4 | + |
| 5 | +// see https://github.com/inferpse/es3-harmony-webpack-plugin |
| 6 | + |
| 7 | +const name = 'ES3HarmonyPlugin'; |
| 8 | + |
| 9 | +module.exports = class ES3HarmonyPlugin { |
| 10 | + apply({hooks, webpack : {javascript : {JavascriptModulesPlugin}}}) { |
| 11 | + // noinspection JSUnresolvedVariable |
| 12 | + hooks.compilation.tap({name}, compilation => { |
| 13 | + // noinspection JSUnresolvedVariable, JSUnresolvedFunction |
| 14 | + JavascriptModulesPlugin.getCompilationHooks(compilation).renderMain.tap({name}, replaceSource) |
| 15 | + }); |
| 16 | + } |
| 17 | +}; |
| 18 | + |
| 19 | +function replaceSource(source) { |
| 20 | + source = source['original'] ? source['original']() : source; |
| 21 | + if (source['getChildren']) { |
| 22 | + source['getChildren']().forEach(replaceSource); |
| 23 | + } else { |
| 24 | + // pattern: RegExp|substr, replacement: newSubstr|function |
| 25 | + replacements.forEach(([pattern, replacement]) => { |
| 26 | + if (pattern.test(source.source())) { |
| 27 | + source._value = source.source().replace(pattern, replacement); |
| 28 | + } |
| 29 | + }); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +const toReplace = (pattern, replacement) => [ |
| 34 | + new RegExp(pattern.trim().replace(/.*noinspection.*\n/g, '').replace(/[?.[\]()]/g, '\\$&').replace(/\s+/g, '\\s*'), 'g'), |
| 35 | + // trimIndent |
| 36 | + replacement.trim().replace(/^ {8}/mg, ''), |
| 37 | +]; |
| 38 | + |
| 39 | +/* global __webpack_require__ */// eslint-disable-line no-unused-vars |
| 40 | +// language=JS |
| 41 | +const replacements = [ |
| 42 | + // @formatter:off |
| 43 | + toReplace(` |
| 44 | + __webpack_require__.d = function (exports, definition) { |
| 45 | + for (var key in definition) { |
| 46 | + // noinspection JSUnfilteredForInLoop, JSUnresolvedFunction |
| 47 | + if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { |
| 48 | + // noinspection JSUnfilteredForInLoop |
| 49 | + Object.defineProperty(exports, key, { enumerable : true, get : definition[key] }); |
| 50 | + } |
| 51 | + } |
| 52 | + }; |
| 53 | + `, ` |
| 54 | + __webpack_require__.d = function (exports, definition) { |
| 55 | + for (var key in definition) { |
| 56 | + // noinspection JSUnfilteredForInLoop, JSUnresolvedFunction |
| 57 | + if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { |
| 58 | + // noinspection JSUnfilteredForInLoop |
| 59 | + exports[key] = definition[key](); // patched by ${name} |
| 60 | + } |
| 61 | + } |
| 62 | + }; |
| 63 | + `), |
| 64 | + // @formatter:on |
| 65 | + |
| 66 | + // remove "use strict" |
| 67 | + [/(['"])use\s+strict(['"]);?/gm, ''], |
| 68 | +]; |
0 commit comments