-
Notifications
You must be signed in to change notification settings - Fork 40
/
index.ts
118 lines (78 loc) · 3.77 KB
/
index.ts
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import { Compiler, WebpackPluginInstance } from 'webpack'
import { Options } from './interfaces'
import { handleSource } from './universal-handler'
import { isStyleFile, isTemplateFile } from './utilities'
import { FileType } from './enum'
import { ConcatSource } from 'webpack-sources'
export default class MiniProgramTailwindWebpackPlugin implements WebpackPluginInstance {
static pluginName = 'mini-program-tailwind-webpack-plugin'
private defaultOptions: Options = {
enableRpx: true,
designWidth: 375,
}
private options: Options
constructor(options?: Options) {
this.options = { ...this.defaultOptions, ...options }
}
apply(compiler: Compiler) {
const isWebpackV5 = compiler.webpack && compiler.webpack.version >= '5'
if (isWebpackV5) {
const { webpack } = compiler
const { sources, Compilation } = webpack
const { ConcatSource } = sources
compiler.hooks.thisCompilation.tap(
MiniProgramTailwindWebpackPlugin.pluginName,
compilation => {
compilation.hooks.processAssets.tap(
{
name: MiniProgramTailwindWebpackPlugin.pluginName,
stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
},
assets => {
for (const pathname in assets) {
const originalSource = assets[ pathname ]
const rawSource = originalSource.source().toString()
let handledSource = ''
if (isStyleFile(pathname)) {
handledSource = handleSource(FileType.Style, rawSource, this.options)
} else if (isTemplateFile(pathname)) {
handledSource = handleSource(FileType.Template, rawSource, this.options)
}
if (handledSource) {
const source = new ConcatSource(handledSource)
compilation.updateAsset(pathname, source)
}
}
},
)
},
)
} else {
compiler.hooks.thisCompilation.tap(
MiniProgramTailwindWebpackPlugin.pluginName,
compilation => {
compilation.hooks.afterOptimizeAssets.tap(
MiniProgramTailwindWebpackPlugin.pluginName,
assets => {
for (const pathname in assets) {
const originalSource = assets[ pathname ]
const rawSource = originalSource.source().toString()
let handledSource = ''
if (isStyleFile(pathname)) {
handledSource = handleSource(FileType.Style, rawSource, this.options)
} else if (isTemplateFile(pathname)) {
handledSource = handleSource(FileType.Template, rawSource, this.options)
}
if (handledSource) {
const source = new ConcatSource(handledSource)
// @ts-ignore
compilation.updateAsset(pathname, source)
}
}
},
)
},
)
}
}
}