1 | function removeJsExt(asset) {
|
2 | return asset.replace(/\.js$/, '')
|
3 | }
|
4 |
|
5 | module.exports = class ZenJsPlugin {
|
6 | constructor(htmlWebpackPlugin) {
|
7 | this.htmlWebpackPlugin = htmlWebpackPlugin
|
8 | }
|
9 |
|
10 | genZenJs(compiler) {
|
11 |
|
12 | compiler.hooks.emit.tap(this.constructor.name, compilation => {
|
13 | const entryNames = Array.from(compilation.entrypoints.keys())
|
14 |
|
15 | entryNames.forEach(entryName => {
|
16 | const entryPointFiles = compilation.entrypoints
|
17 | .get(entryName)
|
18 | .getFiles()
|
19 |
|
20 | entryPointFiles.forEach(chunkFile => {
|
21 | if (!chunkFile.endsWith('.js')) return
|
22 |
|
23 | const name = removeJsExt(chunkFile)
|
24 |
|
25 | compilation.assets[name] = compilation.assets[chunkFile]
|
26 | compilation.assets[name]._fileExt = 'js'
|
27 | })
|
28 | })
|
29 | })
|
30 | }
|
31 |
|
32 | addScriptTypeAttr(compiler) {
|
33 | const pluginName = this.constructor.name
|
34 |
|
35 | compiler.hooks.compilation.tap(pluginName, compilation => {
|
36 | const hooks = this.htmlWebpackPlugin.getHooks(compilation)
|
37 |
|
38 | hooks.alterAssetTags.tap(pluginName, ({ assetTags }) => {
|
39 | assetTags.scripts.forEach(script => {
|
40 | script.attributes = {
|
41 | type: 'text/javascript',
|
42 | src: removeJsExt(script.attributes.src)
|
43 | }
|
44 | })
|
45 | })
|
46 | })
|
47 | }
|
48 |
|
49 | apply(compiler) {
|
50 | this.genZenJs(compiler)
|
51 | this.addScriptTypeAttr(compiler)
|
52 | }
|
53 | }
|