forked from rvanmil/xml-webpack-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
100 lines (96 loc) · 2.45 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const ejs = require('ejs')
const fs = require('fs')
const { join } = require('path')
// eslint-disable-next-line import/no-extraneous-dependencies
const { version } = require('webpack')
const processAssets = (files, compiler, compilation, callback) => {
let compileFailed = false
// Compile all templates
Promise.all(
files.map(file => new Promise((resolve) => {
ejs.renderFile(file.template, file.data, {}, (err, templateString) => {
if (err) {
compilation.errors.push(err)
compileFailed = true
}
file.templateString = templateString
resolve()
})
}))
).then(() => {
// Only continue when compiling templates did not fail
if (compileFailed) {
callback()
return
}
// Split into assets and files to be written to context folder
const xmlFilesForContext = []
files.forEach((file) => {
if (!file.filename) {
compilation.errors.push('XMLWebpackPlugin filename missing', file)
return
}
const xmlPath = file.path || ''
let xmlFilename = join(xmlPath, file.filename)
const xmlContent = file.templateString
if (file.writeToContext) {
// File must be written inside context
xmlFilename = join(compiler.context, xmlFilename)
xmlFilesForContext.push({
filename: xmlFilename,
content: xmlContent
})
} else {
// Regular asset
compilation.assets[xmlFilename] = {
source: () => xmlContent,
size: () => xmlContent.length
}
}
})
// Write files to context folder
if (xmlFilesForContext.length === 0) {
// Nothing to write to context folder, we're done
callback()
return
}
Promise.all(
xmlFilesForContext.map(xmlFile => new Promise((resolve) => {
fs.writeFile(xmlFile.filename, xmlFile.content, (err) => {
if (err) {
compilation.errors.push(err)
}
resolve()
})
}))
).then(() => {
callback()
})
}).catch(() => {
callback()
})
}
class XMLWebpackPlugin {
constructor(options) {
this.files = options.files || []
}
apply(compiler) {
if (version[0] === '4') {
compiler.hooks.emit.tapAsync(
'XMLWebpackPlugin',
(compilation, callback) => processAssets(this.files, compiler, compilation, callback)
)
} else {
compiler.hooks.compilation.tap(
'XMLWebpackPlugin',
(compilation) => {
compilation.hooks.additionalAssets.tapAsync(
'XMLWebpackPlugin',
callback => processAssets(this.files, compiler, compilation, callback)
)
}
)
}
}
}
module.exports = XMLWebpackPlugin