| 34 | } |
| 35 | |
| 36 | export function runWebpack(wpConfig: webpack.Configuration, logLevel: LogLevels): BundleHandlerResponse { |
| 37 | const eventEmitter = new EventEmitter(); |
| 38 | const outDir = wpConfig.output.path; |
| 39 | const bundle = { |
| 40 | outFile: '', |
| 41 | outDir, |
| 42 | name: '', |
| 43 | hash: '', |
| 44 | requireRef: undefined, |
| 45 | }; |
| 46 | |
| 47 | const updateBundle = (stats: webpack.Stats) => { |
| 48 | const file = getOutput(stats); |
| 49 | bundle.name = basename(file); |
| 50 | bundle.requireRef = stats.compilation.outputOptions?.uniqueName; |
| 51 | bundle.hash = stats.hash; |
| 52 | bundle.outFile = `/${basename(file)}`; |
| 53 | bundle.outDir = dirname(file); |
| 54 | }; |
| 55 | |
| 56 | wpConfig.plugins.push({ |
| 57 | apply(compiler: webpack.Compiler) { |
| 58 | compiler.hooks.beforeCompile.tap('piral-cli', () => { |
| 59 | eventEmitter.emit('start'); |
| 60 | }); |
| 61 | |
| 62 | compiler.hooks.done.tap('piral-cli', (stats) => { |
| 63 | updateBundle(stats); |
| 64 | eventEmitter.emit('end', bundle); |
| 65 | }); |
| 66 | }, |
| 67 | }); |
| 68 | |
| 69 | return { |
| 70 | bundle() { |
| 71 | return new Promise((resolve, reject) => { |
| 72 | const preset = { |
| 73 | current: undefined, |
| 74 | }; |
| 75 | |
| 76 | const process = webpack(wpConfig, (err, stats) => { |
| 77 | if (err) { |
| 78 | console.error(err); |
| 79 | reject(err); |
| 80 | } else { |
| 81 | console.log( |
| 82 | stats.toString({ |
| 83 | ...preset.current, |
| 84 | colors: true, |
| 85 | }), |
| 86 | ); |
| 87 | |
| 88 | if (stats.hasErrors()) { |
| 89 | reject(stats.toJson(preset.current)); |
| 90 | } else { |
| 91 | updateBundle(stats); |
| 92 | resolve(bundle); |
| 93 | } |