UNPKG

client-deploy-preview-plugin

Version:

jue deploy preview plugin

91 lines (90 loc) 3.48 kB
const fs = require('fs'); const path = require('path'); const child_process = require('child_process'); const qrcode = require('qrcode-terminal'); const pluginName = 'client-deploy-preview-plugin'; const deployHost = 'https://utest.jr.jd.com' module.exports = class ClientPreviewSimplexPlugin { constructor(options = { index, params }) { this.options = options; } static get DEFAULT_STATS() { return { all: false, hash: true, assets: true, publicPath: true, warnings: false, errors: false, errorDetails: false, }; } chunkSort(chunkNames) { const sort = ['manifest', 'vendor']; chunkNames.sort((a, b) => { const an = sort.indexOf(a) > -1 ? sort.indexOf(a) : 100; const bn = sort.indexOf(b) > -1 ? sort.indexOf(b) : 100; return an - bn; }) return chunkNames; } getStats(statsObj) { const stats = ClientPreviewSimplexPlugin.DEFAULT_STATS; return statsObj.toJson(stats); } getAssets(stats) { const publicPath = stats.publicPath; const chunkNames = Object.keys(stats.assetsByChunkName); this.options.index = this.options.index || chunkNames[0]; return chunkNames.map(name => { const asset = stats.assetsByChunkName[name]; const isIndexPage = this.options.index === name; const launchParams = isIndexPage ? this.options.params : null; let assetPath; if (asset.constructor === Array) { assetPath = `${publicPath}${asset[0]}`; } else { assetPath= `${publicPath}${asset}`; } return { name, asset: assetPath, index: isIndexPage, params: launchParams } }) } deploy(stats) { const nowTimestamp = Date.now(); const __root = process.cwd(); const statsObj = this.getStats(stats) const manifest = this.getAssets(statsObj); const data = new Uint8Array(Buffer.from(JSON.stringify(manifest))); // 要求配置时path和publicPath一致 const outputPath = path.resolve(__root, `dist${statsObj.publicPath}`) const manifestFilePath = path.join(outputPath, `manifest.json`); const emitAssetsSuccess = fs.existsSync(outputPath); if (!emitAssetsSuccess) return; fs.writeFileSync(manifestFilePath, data, (err) => { if (err) throw err console.log('The manifest file has been saved!'); }); const deploy = child_process.spawn('joyer', ['deploy', 'utest', '-d', `dist${statsObj.publicPath}`]); deploy.stdout.on('data', (data) => { }); deploy.stderr.on('data', (data) => { console.log(`${data}`) }); deploy.on('close', code => { if (code === 0) { const accessUrl = `${deployHost}${statsObj.publicPath}manifest.json?t=${nowTimestamp}`; joyer.log.notice(`joyer upload success, ${accessUrl}`) // qrcode.setErrorLevel('Q'); qrcode.generate(accessUrl, {small: true}, function (code) { console.log(code) }); } }) } apply(compiler) { const { done } = compiler.hooks; done.tap(pluginName, stats => this.deploy(stats)); } }