|
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | +const os = require('os'); |
| 4 | +const cpy = require('cpy'); |
| 5 | +const watch = require('@cnakazawa/watch'); |
| 6 | +const { execSync } = require('child_process'); |
| 7 | + |
| 8 | +class WebExtReact { |
| 9 | + buildPath = path.join('build', 'static'); |
| 10 | + assetManifestPath = path.join('build', 'asset-manifest.json'); |
| 11 | + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'race-ext-react-')); |
| 12 | + |
| 13 | + contentByExtention(ext) { |
| 14 | + const assetManifest = JSON.parse(fs.readFileSync(this.assetManifestPath)); |
| 15 | + return assetManifest.entrypoints.filter((filepath) => path.extname(filepath) === ext); |
| 16 | + } |
| 17 | + |
| 18 | + buildApp() { |
| 19 | + execSync('yarn run react-scripts build'); |
| 20 | + } |
| 21 | + |
| 22 | + buildExt() { |
| 23 | + if (fs.existsSync(this.assetManifestPath)) { |
| 24 | + const extManifest = JSON.parse(fs.readFileSync('extension/manifest.json')); |
| 25 | + extManifest.content_scripts[0].js = this.contentByExtention('.js'); |
| 26 | + extManifest.content_scripts[0].css = this.contentByExtention('.css'); |
| 27 | + fs.writeFileSync(path.join(this.tmp, 'manifest.json'), JSON.stringify(extManifest)); |
| 28 | + cpy('.', path.join(this.tmp, 'static'), { parents: true, cwd: this.buildPath }); |
| 29 | + return this.tmp; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + build() { |
| 34 | + this.buildApp(); |
| 35 | + const dir = this.buildExt(); |
| 36 | + process.stdout.write(`${dir}\n`); |
| 37 | + } |
| 38 | + |
| 39 | + run() { |
| 40 | + this.watchAppSrc(); |
| 41 | + this.watchAppBuild(); |
| 42 | + } |
| 43 | + |
| 44 | + watchAppSrc() { |
| 45 | + watch.watchTree('src', () => { |
| 46 | + this.buildApp(); |
| 47 | + }) |
| 48 | + } |
| 49 | + |
| 50 | + watchAppBuild() { |
| 51 | + watch.watchTree('build', { filter: (f) => { |
| 52 | + return f === this.assetManifestPath; |
| 53 | + }}, () => { |
| 54 | + const sourceDir = this.buildExt(); |
| 55 | + process.stdout.write(`${sourceDir}\n`); |
| 56 | + }) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +module.exports = WebExtReact; |
0 commit comments