-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebpack.config.ts
More file actions
executable file
·363 lines (349 loc) · 11.2 KB
/
webpack.config.ts
File metadata and controls
executable file
·363 lines (349 loc) · 11.2 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import HtmlInlineScriptWebpackPlugin from 'html-inline-script-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
import url from 'node:url';
import { Server } from 'socket.io';
import TerserPlugin from 'terser-webpack-plugin';
import TsconfigPathsPlugin from 'tsconfig-paths-webpack-plugin';
import { VueLoaderPlugin } from 'vue-loader';
import webpack from 'webpack';
import WebpackObfuscator from 'webpack-obfuscator';
const require = createRequire(import.meta.url);
const HTMLInlineCSSWebpackPlugin = require('html-inline-css-webpack-plugin').default;
const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
interface Config {
port: number;
entries: Entry[];
}
interface Entry {
script: string;
html?: string;
}
function parse_entry(script_file: string) {
const html = path.join(path.dirname(script_file), 'index.html');
if (fs.existsSync(html)) {
return { script: script_file, html };
}
return { script: script_file };
}
function common_path(lhs: string, rhs: string) {
const lhs_parts = lhs.split(path.sep);
const rhs_parts = rhs.split(path.sep);
for (let i = 0; i < Math.min(lhs_parts.length, rhs_parts.length); i++) {
if (lhs_parts[i] !== rhs_parts[i]) {
return lhs_parts.slice(0, i).join(path.sep);
}
}
return lhs_parts.join(path.sep);
}
function glob_script_files() {
const files: string[] = fs
.globSync(`src/**/index.{ts,js}`)
.filter(file => process.env.CI !== 'true' || !fs.readFileSync(path.join(__dirname, file)).includes('@no-ci'));
const results: string[] = [];
const handle = (file: string) => {
const file_dirname = path.dirname(file);
for (const [index, result] of results.entries()) {
const result_dirname = path.dirname(result);
const common = common_path(result_dirname, file_dirname);
if (common === result_dirname) {
return;
}
if (common === file_dirname) {
results.splice(index, 1, file);
return;
}
}
results.push(file);
};
files.forEach(handle);
return results;
}
const config: Config = {
port: 6621,
entries: glob_script_files().map(parse_entry),
};
let io: Server;
function watch_it(compiler: webpack.Compiler) {
if (compiler.options.watch) {
if (!io) {
const port = config.port ?? 6621;
io = new Server(port, { cors: { origin: '*' } });
console.info(`[Listener] 已启动酒馆监听服务, 正在监听: http://0.0.0.0:${port}`);
io.on('connect', socket => {
console.info(`[Listener] 成功连接到酒馆网页 '${socket.id}', 初始化推送...`);
io.emit('iframe_updated');
socket.on('disconnect', reason => {
console.info(`[Listener] 与酒馆网页 '${socket.id}' 断开连接: ${reason}`);
});
});
}
compiler.hooks.done.tap('updater', () => {
console.info('\n[Listener] 检测到完成编译, 推送更新事件...');
io.emit('iframe_updated');
});
}
}
function parse_configuration(entry: Entry): (_env: any, argv: any) => webpack.Configuration {
const should_obfuscate = fs.readFileSync(path.join(__dirname, entry.script), 'utf-8').includes('@obfuscate');
const script_filepath = path.parse(entry.script);
return (_env, argv) => ({
experiments: {
outputModule: true,
},
devtool: argv.mode === 'production' ? false : 'eval-source-map',
watchOptions: {
ignored: ['**/dist', '**/node_modules'],
},
entry: path.join(__dirname, entry.script),
target: 'browserslist',
output: {
devtoolModuleFilenameTemplate: 'webpack://tavern_helper_template/[resource-path]?[loaders]',
filename: `${script_filepath.name}.js`,
path: path.join(__dirname, 'dist', path.relative(path.join(__dirname, 'src'), script_filepath.dir)),
chunkFilename: `${script_filepath.name}.[contenthash].chunk.js`,
asyncChunks: true,
chunkLoading: 'import',
clean: true,
publicPath: '',
library: {
type: 'module',
},
},
module: {
rules: [
{
test: /\.vue$/,
use: 'vue-loader',
exclude: /node_modules/,
},
{
oneOf: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
transpileOnly: false,
onlyCompileBundledFiles: true,
appendTsSuffixTo: [/\.vue$/],
compilerOptions: {
noUnusedLocals: false,
noUnusedParameters: false,
},
},
resourceQuery: /raw/,
type: 'asset/source',
exclude: /node_modules/,
},
{
test: /\.(sa|sc)ss$/,
use: ['postcss-loader', 'sass-loader'],
resourceQuery: /raw/,
type: 'asset/source',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: ['postcss-loader'],
resourceQuery: /raw/,
type: 'asset/source',
exclude: /node_modules/,
},
{
resourceQuery: /raw/,
type: 'asset/source',
exclude: /node_modules/,
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
transpileOnly: false,
onlyCompileBundledFiles: true,
appendTsSuffixTo: [/\.vue$/],
compilerOptions: {
noUnusedLocals: false,
noUnusedParameters: false,
},
},
exclude: /node_modules/,
},
{
test: /\.html?$/,
use: 'html-loader',
exclude: /node_modules/,
},
].concat(
entry.html === undefined
? <any[]>[
{
test: /\.vue\.s(a|c)ss$/,
use: [
{ loader: 'vue-style-loader', options: { ssrId: true } },
{ loader: 'css-loader', options: { url: false } },
'postcss-loader',
'sass-loader',
],
exclude: /node_modules/,
},
{
test: /\.vue\.css$/,
use: [
{ loader: 'vue-style-loader', options: { ssrId: true } },
{ loader: 'css-loader', options: { url: false } },
'postcss-loader',
],
exclude: /node_modules/,
},
{
test: /\.s(a|c)ss$/,
use: [{ loader: 'css-loader', options: { url: false } }, 'postcss-loader', 'sass-loader'],
exclude: /node_modules/,
},
{
test: /\.css$/,
use: [{ loader: 'css-loader', options: { url: false } }, 'postcss-loader'],
exclude: /node_modules/,
},
]
: <any[]>[
{
test: /\.s(a|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { url: false } },
'postcss-loader',
'sass-loader',
],
exclude: /node_modules/,
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { url: false } },
'postcss-loader',
],
exclude: /node_modules/,
},
],
),
},
],
},
resolve: {
extensions: ['.ts', '.js', '.tsx', '.jsx', '.css'],
plugins: [
new TsconfigPathsPlugin({
extensions: ['.ts', '.js', '.tsx', '.jsx'],
configFile: path.join(__dirname, 'tsconfig.json'),
}),
],
alias: {},
},
plugins: (entry.html === undefined
? [new MiniCssExtractPlugin()]
: [
new HtmlWebpackPlugin({
template: path.join(__dirname, entry.html),
filename: path.parse(entry.html).base,
scriptLoading: 'module',
cache: false,
}),
new HtmlInlineScriptWebpackPlugin(),
new MiniCssExtractPlugin(),
new HTMLInlineCSSWebpackPlugin({
styleTagFactory({ style }: { style: string }) {
return `<style>${style}</style>`;
},
}),
]
)
.concat({ apply: watch_it }, new VueLoaderPlugin())
.concat(
should_obfuscate
? [
new WebpackObfuscator({
controlFlowFlattening: true,
numbersToExpressions: true,
selfDefending: true,
simplify: true,
splitStrings: true,
}),
]
: [],
),
optimization: {
minimize: true,
minimizer: [
argv.mode === 'production'
? new TerserPlugin({
terserOptions: { format: { quote_style: 1 }, mangle: { reserved: ['_', 'toastr', 'YAML', '$', 'z'] } },
})
: new TerserPlugin({
extractComments: false,
terserOptions: {
format: { beautify: true, indent_level: 2 },
compress: false,
mangle: false,
},
}),
],
splitChunks: {
chunks: 'async',
minSize: 20000,
minChunks: 1,
maxAsyncRequests: 30,
maxInitialRequests: 30,
cacheGroups: {
vendor: {
name: 'vendor',
test: /[\\/]node_modules[\\/]/,
priority: -10,
},
default: {
name: 'default',
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
},
},
},
},
externals: ({ context, request }, callback) => {
if (!context || !request) {
return callback();
}
if (
request.startsWith('-') ||
request.startsWith('.') ||
request.startsWith('/') ||
request.startsWith('!') ||
request.startsWith('http') ||
path.isAbsolute(request) ||
fs.existsSync(path.join(context, request)) ||
fs.existsSync(request)
) {
return callback();
}
const builtin = {
jquery: '$',
lodash: '_',
toastr: 'toastr',
vue: 'Vue',
'vue-router': 'VueRouter',
yaml: 'YAML',
zod: 'z',
};
if (request in builtin) {
return callback(null, 'var ' + builtin[request as keyof typeof builtin]);
}
return callback(null, 'module-import https://testingcf.jsdelivr.net/npm/' + request + '/+esm');
},
});
}
export default config.entries.map(parse_configuration);