-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweballpacka.js
More file actions
328 lines (291 loc) · 12.8 KB
/
Copy pathweballpacka.js
File metadata and controls
328 lines (291 loc) · 12.8 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
const path = require('path');
const fs = require('fs');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');
const postcssPurgecss = require('@fullhuman/postcss-purgecss');
function utilityCssExtractor(content) {
return content.match(/[a-zA-Z0-9-_.:@\/]+/g);
}
function createMergedWebpackConfig(gulp, $, config) {
const argv = require('minimist')(process.argv.slice(2));
const purgeCssDisabled = argv.purgecss === false;
const isDevServer = process.argv.includes('serve') || process.env.WEBPACK_SERVE === 'true';
const isDev = config.development && argv.prod !== true;
const entry = {};
const entryCssMeta = {};
// ---- CSS entries ----
(config.styles.files || []).forEach((file) => {
// key must be unique and stable
const entryName = `css_${file.name.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
entry[entryName] = path.resolve(config.webdir, file.inputPath);
entryCssMeta[entryName] = {
destDir: file.destDir || 'css',
filename: file.name,
resolvedInputPath: path.resolve(config.webdir, file.inputPath),
purgeCssConfig: file.purgeCss ?? config.styles.purgeCss ?? null,
postCssPresetEnvConfig: file.postCssPresetEnv || config.styles.postCssPresetEnv || {},
};
});
// ---- JS entries ----
let includeModules = config.scripts.includeModules ? '|' + config.scripts.includeModules.join('|') : '';
let svelteVersion = config.svelteVersion ? parseFloat(config.svelteVersion) : 3;
let resolveModulesPaths = [config.npmdir];
if (config.scripts.resolveModulesPaths) {
resolveModulesPaths = [...new Set([...(config.scripts.resolveModulesPaths), ...resolveModulesPaths])];
}
(config.scripts.files || []).forEach((script) => {
const entryName = `js_${script.name.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
entry[entryName] = path.resolve(config.webdir, script.inputPath);
});
// ---- Dev Server Configuration ----
const devServerPort = 3000;
const devServerHost = config.proxyUrl || 'localhost';
const devServerPublicPath = `http://${devServerHost}:${devServerPort}/`;
// Watch paths for PHP/Twig files (triggers full reload)
const watchPaths = config.watchPaths;
const webpackConfig = {
entry,
output: {
// js_<name> -> js/<name>.js
filename: (pathData) => {
const name = pathData.chunk && pathData.chunk.name ? pathData.chunk.name : '[name]';
if (name.startsWith('js_')) {
const cleanName = name.replace(/^js_/, '');
return `js/${cleanName}.js`;
}
return '[name].js';
},
path: path.resolve(config.webdir),
},
resolve: {
alias: {
svelte: svelteVersion < 4
? $.path.resolve('node_modules', 'svelte')
: $.path.resolve('node_modules', 'svelte/src/runtime')
},
extensions: ['.mjs', '.js', '.svelte', '.ts'],
mainFields: ['svelte', 'browser', 'module', 'main'],
modules: resolveModulesPaths,
},
watchOptions: {
poll: 1000,
ignored: /node_modules/,
},
module: {
rules: [
// JS + Svelte + Typescript
{
test: /(\.m?js?$)|(\.svelte$)/,
exclude: new RegExp('node_modules\\/(?![svelte' + includeModules + '])'),
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-transform-runtime'],
}
}
},
{
test: /\.(html|svelte)$/,
exclude: /node_modules\/(?!svelte)/,
use: [
'babel-loader',
{
loader: 'svelte-loader',
options: {
cacheDirectory: true,
emitCss: false,
// Enable HMR for Svelte components
hotReload: isDevServer && isDev,
},
},
],
},
{
// required to prevent errors from Svelte on Webpack 5+, omit on Webpack 4
test: /node_modules\/svelte\/.*\.mjs$/,
resolve: {
fullySpecified: false,
}
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
// Assets used from SCSS
{
test: /\.(png|jpe?g|gif|svg|webp|avif)$/i,
type: 'asset/resource',
generator: {
filename: 'img/[name].[hash][ext]'
}
},
// SCSS -> CSS (via MiniCssExtractPlugin)
{
test: /\.s[ac]ss$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: { sourceMap: true }
},
{
loader: 'resolve-url-loader',
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
postcssOptions: (loaderContext) => {
let cssEntry = null;
// Resolve the real path of the resource (resolves symlinks)
let realResourcePath = fs.realpathSync(loaderContext.resourcePath);
for (const [entryName, meta] of Object.entries(entryCssMeta)) {
if (meta.resolvedInputPath) {
const realInputPath = fs.realpathSync(meta.resolvedInputPath);
if (realResourcePath === realInputPath) {
cssEntry = meta;
break;
}
}
}
if (!cssEntry) {
throw new Error(
`No CSS entry metadata found for resource: ${loaderContext.resourcePath}\n` +
`Real path: ${realResourcePath}\n` +
`Available entries: ${Object.keys(entryCssMeta).join(', ')}\n` +
`Entry paths: ${Object.values(entryCssMeta).map(m => m.resolvedInputPath).join(', ')}\n` +
`Ensure the SCSS file is an exact webpack entry point from config.styles.files[].inputPath`
);
}
const postCssPresetEnvConfig = cssEntry.postCssPresetEnvConfig || {};
return {
plugins: [
require('postcss-preset-env')(postCssPresetEnvConfig),
...(cssEntry.purgeCssConfig && !purgeCssDisabled
? [postcssPurgecss({
content: cssEntry.purgeCssConfig.content,
extractors: [{
extractor: utilityCssExtractor,
extensions: ['php', 'twig', 'js', 'svg']
}],
safelist: cssEntry.purgeCssConfig.safelist,
})]
: []),
],
};
},
},
},
{
loader: 'sass-loader',
options: {
implementation: 'sass-embedded',
api: 'modern',
sourceMap: true,
sassOptions: {
loadPaths: [...new Set([
...(config.styles.includePaths || []),
config.npmdir,
'www/bundles'
])],
},
},
},
],
},
],
},
plugins: [
new $.webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
}),
// Removes empty `.js` files left over by MiniCssExtractPlugin
new RemoveEmptyScriptsPlugin(),
// CSS extraction with per‑entry filenames
new MiniCssExtractPlugin({
filename: (pathData) => {
const name = pathData.chunk && pathData.chunk.name ? pathData.chunk.name : '[name]';
if (name.startsWith('css_')) {
const meta = entryCssMeta[name];
if (meta) {
const dir = meta.destDir ? meta.destDir.replace(/\/+$/, '') : 'css';
return `${dir}/${meta.filename}`;
}
}
// fallback
return 'css/[name].css';
},
}),
],
// ---- Dev Server ----
devServer: {
hot: false,
liveReload: true,
host: devServerHost,
port: devServerPort,
allowedHosts: 'all',
// Allow connections from your PHP server
allowedHosts: 'all',
// Watch PHP/Twig files for full page reload
watchFiles: {
paths: watchPaths,
options: {
usePolling: false,
ignored: /node_modules/,
followSymlinks: true,
},
},
// Client overlay for errors
client: {
overlay: {
errors: true,
warnings: false,
},
progress: true,
webSocketURL: {
hostname: devServerHost,
port: 3000,
},
},
},
mode: isDev ? 'development' : 'production',
devtool: $.argv.debug === true ? 'source-map' : (isDev ? 'eval-source-map' : false),
stats: {
preset: 'normal',
timings: true,
},
};
return webpackConfig;
}
/**
* Gulp task for production builds (no dev server)
*/
function webpackMerged(gulp, $, config) {
const webpackStream = require('webpack-stream');
const webpack = $.webpack;
const webpackConfig = createMergedWebpackConfig(gulp, $, config);
// Remove devServer from gulp builds
delete webpackConfig.devServer;
return gulp.src(config.webdir + '/**/*.{js,scss}')
.pipe(webpackStream(webpackConfig, webpack))
.pipe(gulp.dest(config.webdir));
}
/**
* Start webpack-dev-server for development with LiveReload
*/
function webpackServe(gulp, $, config, done) {
const webpack = $.webpack;
const WebpackDevServer = require('webpack-dev-server');
const webpackConfig = createMergedWebpackConfig(gulp, $, config);
const compiler = webpack(webpackConfig);
const devServerOptions = webpackConfig.devServer;
const server = new WebpackDevServer(devServerOptions, compiler);
server.start();
}
exports.webpackMerged = webpackMerged;
exports.createMergedWebpackConfig = createMergedWebpackConfig;
exports.webpackServe = webpackServe;