| 15 | } |
| 16 | |
| 17 | apply(compiler) { |
| 18 | const { entryName, typescriptFile, filename } = this.options; |
| 19 | |
| 20 | if (entryName && typescriptFile) { |
| 21 | const context = compiler.context || compiler.options.context; |
| 22 | const entry = new webpack.EntryPlugin( |
| 23 | context, |
| 24 | 'expose-loader?exposes=_extractJson!' + typescriptFile, |
| 25 | { |
| 26 | name: entryName, |
| 27 | filename: '../temp/[name].js' |
| 28 | }, |
| 29 | ); |
| 30 | entry.apply(compiler); |
| 31 | } |
| 32 | |
| 33 | compiler.hooks.afterEmit.tapAsync('ExtractJsonPlugin', (compilation, callback) => { |
| 34 | const entrypoint = compilation.entrypoints.get(entryName); |
| 35 | if (!entrypoint) { |
| 36 | const error = new Error(`ExtractJsonPlugin: Entry '${entryName}' not found`); |
| 37 | return callback(error); |
| 38 | } |
| 39 | |
| 40 | const outputFiles = entrypoint.getFiles(); |
| 41 | if (!outputFiles.length) { |
| 42 | const error = new Error(`ExtractJsonPlugin: No output files found for entry '${entryName}'`); |
| 43 | return callback(error); |
| 44 | } |
| 45 | |
| 46 | const outputFile = outputFiles[0]; |
| 47 | const outputPath = path.join(compiler.outputPath, outputFile); |
| 48 | |
| 49 | setTimeout(() => { |
| 50 | try { |
| 51 | const require = createRequire(import.meta.url); |
| 52 | |
| 53 | if (require.cache[outputPath]) { |
| 54 | delete require.cache[outputPath]; |
| 55 | } |
| 56 | delete globalThis._extractJson; |
| 57 | global.jQuery = {}; |
| 58 | const module = require(outputPath); |
| 59 | const jsonData = globalThis._extractJson.default(); |
| 60 | |
| 61 | if (this.options.folderMode) { |
| 62 | const folderPath = path.join(compiler.outputPath, filename); |
| 63 | |
| 64 | if (!fs.existsSync(folderPath)) { |
| 65 | fs.mkdirSync(folderPath, { recursive: true }); |
| 66 | } |
| 67 | |
| 68 | for (const [key, value] of Object.entries(jsonData)) { |
| 69 | const filePath = path.join(folderPath, `${key}.json`); |
| 70 | const jsonString = JSON.stringify(value, null, 2); |
| 71 | fs.writeFileSync(filePath, jsonString); |
| 72 | |
| 73 | const stats = fs.statSync(filePath); |
| 74 | |