UNPKG

jsxbin-webpack-plugin

Version:

A Webpack plugin to JSXbin-pack Extendscript outputs.

94 lines (74 loc) 3.14 kB
"use strict"; function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } const ModuleFilenameHelpers = require('webpack/lib/ModuleFilenameHelpers'); const os = require('os'); const path = require('path'); const fs = require('fs'); const _require = require('webpack-sources'), RawSource = _require.RawSource; class JSXBinWebpackPlugin { constructor(options) { if (typeof options !== 'object') { throw new TypeError('Argument "options" must be an object.'); } this.test = options.test; try { this.jsxbin = require('jsxbin'); } catch (err) { console.warn('jsxbin package not found. Not compiling jsx assets.'); this.jsxbin = null; } } _compileFile(compilation, fileName) { var _this = this; return _asyncToGenerator(function* () { const jsxFilename = fileName.replace('.js', '.jsxbin'); const temporaryJSDestination = path.join(os.tmpdir(), fileName); const temporaryJSXDestination = path.join(os.tmpdir(), jsxFilename); if (fs.existsSync(temporaryJSDestination)) { fs.unlinkSync(temporaryJSDestination); } if (fs.existsSync(temporaryJSXDestination)) { fs.unlinkSync(temporaryJSXDestination); } fs.writeFileSync(temporaryJSDestination, compilation.assets[fileName].source()); yield _this.jsxbin(temporaryJSDestination, temporaryJSXDestination); const jsxContents = fs.readFileSync(temporaryJSXDestination, 'utf8'); fs.unlinkSync(temporaryJSXDestination); compilation.assets[jsxFilename] = new RawSource(jsxContents); delete compilation.assets[fileName]; })(); } _compileChunks(compilation, chunks) { var _this2 = this; return _asyncToGenerator(function* () { const promises = []; chunks.forEach(chunk => { chunk.files.forEach(fileName => { if (ModuleFilenameHelpers.matchObject({ test: _this2.test }, fileName)) { promises.push(_this2._compileFile(compilation, fileName)); } }); }); return Promise.all(promises); })(); } apply(compiler) { if (this.jsxbin) { const plugin = { name: this.constructor.name }; compiler.hooks.compilation.tap(plugin, compilation => { compilation.hooks.optimizeChunkAssets.tapAsync(plugin, (chunks, done) => { this._compileChunks(compilation, chunks).then(() => { done(); }); }); }); } } } module.exports = JSXBinWebpackPlugin;