refactor pagebuilder asset bundling
Migrate pagebuilder and core dist assets from legacy bundled format to modern Vite/Rolldown output. - Delete legacy pagebuilder app.css and app.js bundles in favor of per-module dist files. - Update page-injection.js to use template literals and add source map reference. - Refresh core dist files (PageBuilderBody, PageBuilderHead, WebsiteManager) with updated CSS/JS and remove UMD bundles.
This commit is contained in:
+291
-99
@@ -1,107 +1,299 @@
|
||||
import { build } from 'vite';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { rolldown } from 'rolldown';
|
||||
import * as sass from 'sass';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const isWatch = process.argv.includes('--watch') || process.argv.includes('-w');
|
||||
const isDev = isWatch || process.env.NODE_ENV === 'development';
|
||||
|
||||
// libraries
|
||||
const libraries = [
|
||||
{
|
||||
entry: './src/Modules/WebsiteManager/resources/assets/entry.js',
|
||||
name: 'WebsiteManager',
|
||||
fileName: 'WebsiteManager',
|
||||
},
|
||||
{
|
||||
entry: './src/Modules/GrapesJS/resources/assets/entryHead.js',
|
||||
name: 'PageBuilderHead',
|
||||
fileName: 'PageBuilderHead',
|
||||
},
|
||||
{
|
||||
entry: './src/Modules/GrapesJS/resources/assets/entryBody.js',
|
||||
name: 'PageBuilderBody',
|
||||
fileName: 'PageBuilderBody',
|
||||
},
|
||||
];
|
||||
const GRAPES_JS_PATH = path.resolve(__dirname, 'node_modules/grapesjs/dist/grapes.min.js');
|
||||
const GRAPES_CSS_PATH = path.resolve(__dirname, 'node_modules/grapesjs/dist/css/grapes.min.css');
|
||||
const DIST_DIR = path.resolve(__dirname, 'dist');
|
||||
const DIST_PB_DIR = path.resolve(DIST_DIR, 'pagebuilder');
|
||||
|
||||
// GrapesJS ships a pre-bundled Webpack bundle as its ESM entry (grapes.mjs).
|
||||
// Vite cannot re-bundle it correctly because the internal __webpack_require__
|
||||
// calls break when Vite replaces the module system. Use a custom plugin to
|
||||
// inject the raw GrapesJS UMD bundle and resolve the import to it.
|
||||
function grapesjsBundlePlugin() {
|
||||
const grapesMinPath = path.resolve(__dirname, 'node_modules/grapesjs/dist/grapes.min.js');
|
||||
const grapesMinContent = fs.readFileSync(grapesMinPath, 'utf-8');
|
||||
|
||||
return [
|
||||
{
|
||||
name: 'grapesjs-resolve',
|
||||
resolveId(id, importer) {
|
||||
if (id === 'grapesjs') {
|
||||
return { id: '\0grapesjs-umd', moduleSideEffects: true };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
load(id) {
|
||||
if (id === '\0grapesjs-umd') {
|
||||
// Return the UMD bundle as a raw module that sets window.grapesjs
|
||||
return `window.grapesjs = undefined;
|
||||
${grapesMinContent}
|
||||
var _grapesjs = window.grapesjs;
|
||||
export default _grapesjs;`;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
// Prevent Rollup from trying to scan/transform this module
|
||||
moduleParsed(info) {
|
||||
if (info.id === '\0grapesjs-umd') {
|
||||
info.isEntry = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'grapesjs-output',
|
||||
renderChunk(code) {
|
||||
// The GrapesJS UMD bundle uses __webpack_modules__ which Rollup might rename.
|
||||
// We need to ensure the output preserves the Webpack bundle structure.
|
||||
return null;
|
||||
},
|
||||
},
|
||||
];
|
||||
function ensureDirectories() {
|
||||
fs.mkdirSync(DIST_DIR, { recursive: true });
|
||||
fs.mkdirSync(DIST_PB_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function verifyPreconditions() {
|
||||
if (!fs.existsSync(GRAPES_JS_PATH)) {
|
||||
console.error(`\x1b[31mError:\x1b[0m GrapesJS JavaScript bundle not found at: ${GRAPES_JS_PATH}`);
|
||||
console.error("Please run 'npm install' before building plugi-core.");
|
||||
process.exit(1);
|
||||
}
|
||||
if (!fs.existsSync(GRAPES_CSS_PATH)) {
|
||||
console.error(`\x1b[31mError:\x1b[0m GrapesJS CSS bundle not found at: ${GRAPES_CSS_PATH}`);
|
||||
console.error("Please run 'npm install' before building plugi-core.");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// build
|
||||
libraries.forEach(async (libItem) => {
|
||||
await build({
|
||||
configFile: false,
|
||||
plugins: [grapesjsBundlePlugin()],
|
||||
build: {
|
||||
lib: libItem,
|
||||
emptyOutDir: false,
|
||||
minify: 'terser',
|
||||
terserOptions: {
|
||||
mangle: {
|
||||
// Reserve names that are used as globals in pagebuilder.php to prevent
|
||||
// the minifier from generating them as mangled variable names
|
||||
reserved: ['config', 'editor', 'window', 'document', 'console', 'CKEDITOR'],
|
||||
},
|
||||
compress: {
|
||||
// Preserve __webpack_* variable names used by the GrapesJS Webpack bundle
|
||||
keep_fargs: false,
|
||||
},
|
||||
format: {
|
||||
// Preserve __webpack_* variable names from being mangled
|
||||
keep_quoted_props: true,
|
||||
},
|
||||
},
|
||||
rollupOptions: {
|
||||
output: {
|
||||
assetFileNames: (assetInfo) => {
|
||||
if (assetInfo.name === 'style.css') return `${libItem.fileName}.css`;
|
||||
return assetInfo.name;
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
function cleanObsoleteArtifacts() {
|
||||
const obsoleteFiles = [
|
||||
path.join(DIST_DIR, 'PageBuilderBody.css'),
|
||||
path.join(DIST_DIR, 'PageBuilderBody.css.map'),
|
||||
path.join(DIST_DIR, 'PageBuilderBody.umd.cjs'),
|
||||
path.join(DIST_DIR, 'PageBuilderHead.umd.cjs'),
|
||||
path.join(DIST_DIR, 'WebsiteManager.umd.cjs'),
|
||||
path.join(DIST_PB_DIR, 'app.css'),
|
||||
path.join(DIST_PB_DIR, 'app.css.map'),
|
||||
path.join(DIST_PB_DIR, 'app.js'),
|
||||
path.join(DIST_PB_DIR, 'app.js.map'),
|
||||
];
|
||||
|
||||
for (const file of obsoleteFiles) {
|
||||
if (fs.existsSync(file)) {
|
||||
try {
|
||||
fs.unlinkSync(file);
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function bundleJs(input, output, { minify = !isDev } = {}) {
|
||||
const start = performance.now();
|
||||
const bundle = await rolldown({ input });
|
||||
await bundle.write({
|
||||
file: output,
|
||||
format: 'iife',
|
||||
sourcemap: true,
|
||||
minify,
|
||||
});
|
||||
});
|
||||
const duration = (performance.now() - start).toFixed(1);
|
||||
const relOutput = path.relative(__dirname, output);
|
||||
const size = (fs.statSync(output).size / 1024).toFixed(1);
|
||||
console.log(` \x1b[32m✓\x1b[0m JS ${relOutput} (${size} kB, ${duration}ms)`);
|
||||
}
|
||||
|
||||
function compileSass(input, output) {
|
||||
const start = performance.now();
|
||||
const result = sass.compile(input, {
|
||||
style: 'compressed',
|
||||
sourceMap: true,
|
||||
});
|
||||
|
||||
let css = result.css;
|
||||
const mapFileName = `${path.basename(output)}.map`;
|
||||
css += `\n/*# sourceMappingURL=${mapFileName} */`;
|
||||
|
||||
fs.writeFileSync(output, css);
|
||||
if (result.sourceMap) {
|
||||
fs.writeFileSync(`${output}.map`, JSON.stringify(result.sourceMap));
|
||||
}
|
||||
|
||||
const duration = (performance.now() - start).toFixed(1);
|
||||
const relOutput = path.relative(__dirname, output);
|
||||
const size = (fs.statSync(output).size / 1024).toFixed(1);
|
||||
console.log(` \x1b[32m✓\x1b[0m Sass ${relOutput} (${size} kB, ${duration}ms)`);
|
||||
}
|
||||
|
||||
function buildGrapesHead() {
|
||||
const start = performance.now();
|
||||
|
||||
// 1. Copy GrapesJS minified script directly
|
||||
const headJsOutput = path.join(DIST_DIR, 'PageBuilderHead.js');
|
||||
fs.copyFileSync(GRAPES_JS_PATH, headJsOutput);
|
||||
|
||||
// 2. Concatenate GrapesJS core CSS and compiled custom SCSS
|
||||
const headCssOutput = path.join(DIST_DIR, 'PageBuilderHead.css');
|
||||
const grapesCss = fs.readFileSync(GRAPES_CSS_PATH, 'utf-8');
|
||||
const customSassResult = sass.compile(
|
||||
path.resolve(__dirname, 'src/Modules/GrapesJS/resources/assets/sass/app.scss'),
|
||||
{ style: 'compressed', sourceMap: true }
|
||||
);
|
||||
|
||||
const combinedCss = `${grapesCss}\n${customSassResult.css}\n/*# sourceMappingURL=PageBuilderHead.css.map */`;
|
||||
fs.writeFileSync(headCssOutput, combinedCss);
|
||||
|
||||
if (customSassResult.sourceMap) {
|
||||
fs.writeFileSync(`${headCssOutput}.map`, JSON.stringify(customSassResult.sourceMap));
|
||||
}
|
||||
|
||||
const duration = (performance.now() - start).toFixed(1);
|
||||
const jsSize = (fs.statSync(headJsOutput).size / 1024).toFixed(1);
|
||||
const cssSize = (fs.statSync(headCssOutput).size / 1024).toFixed(1);
|
||||
console.log(` \x1b[32m✓\x1b[0m GJS dist/PageBuilderHead.js (${jsSize} kB) & .css (${cssSize} kB) (${duration}ms)`);
|
||||
}
|
||||
|
||||
async function buildGrapesBody() {
|
||||
await bundleJs(
|
||||
path.resolve(__dirname, 'src/Modules/GrapesJS/resources/assets/js/app.js'),
|
||||
path.join(DIST_DIR, 'PageBuilderBody.js'),
|
||||
{ minify: !isDev }
|
||||
);
|
||||
}
|
||||
|
||||
async function buildPageInjectionJs() {
|
||||
await bundleJs(
|
||||
path.resolve(__dirname, 'src/Modules/GrapesJS/resources/assets/js/page-injection.js'),
|
||||
path.join(DIST_PB_DIR, 'page-injection.js'),
|
||||
{ minify: !isDev }
|
||||
);
|
||||
}
|
||||
|
||||
function buildPageInjectionCss() {
|
||||
compileSass(
|
||||
path.resolve(__dirname, 'src/Modules/GrapesJS/resources/assets/sass/page-injection.scss'),
|
||||
path.join(DIST_PB_DIR, 'page-injection.css')
|
||||
);
|
||||
}
|
||||
|
||||
async function buildWebsiteManagerJs() {
|
||||
await bundleJs(
|
||||
path.resolve(__dirname, 'src/Modules/WebsiteManager/resources/assets/js/main.js'),
|
||||
path.join(DIST_DIR, 'WebsiteManager.js'),
|
||||
{ minify: !isDev }
|
||||
);
|
||||
}
|
||||
|
||||
function runTailwindCli({ watch = false } = {}) {
|
||||
const input = path.resolve(__dirname, 'src/Modules/WebsiteManager/resources/assets/css/style.css');
|
||||
const output = path.join(DIST_DIR, 'WebsiteManager.css');
|
||||
const tailwindBin = path.resolve(__dirname, 'node_modules/.bin/tailwindcss');
|
||||
|
||||
const args = ['-i', input, '-o', output];
|
||||
if (!isDev) {
|
||||
args.push('--minify');
|
||||
}
|
||||
if (watch) {
|
||||
args.push('--watch');
|
||||
}
|
||||
|
||||
if (watch) {
|
||||
const child = spawn(tailwindBin, args, { stdio: 'inherit', cwd: __dirname });
|
||||
return child;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const start = performance.now();
|
||||
const child = spawn(tailwindBin, args, { stdio: 'pipe', cwd: __dirname });
|
||||
let stderr = '';
|
||||
|
||||
child.stderr.on('data', (d) => {
|
||||
stderr += d.toString();
|
||||
});
|
||||
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) {
|
||||
const duration = (performance.now() - start).toFixed(1);
|
||||
const size = (fs.statSync(output).size / 1024).toFixed(1);
|
||||
console.log(` \x1b[32m✓\x1b[0m CSS dist/WebsiteManager.css (${size} kB, ${duration}ms)`);
|
||||
resolve();
|
||||
} else {
|
||||
console.error(`\x1b[31mError compiling Tailwind CSS:\x1b[0m\n${stderr}`);
|
||||
reject(new Error(`Tailwind CLI exited with code ${code}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function buildAll() {
|
||||
const totalStart = performance.now();
|
||||
console.log(`\n\x1b[1mBuilding plugi-core assets (${isDev ? 'development' : 'production'})...\x1b[0m`);
|
||||
|
||||
ensureDirectories();
|
||||
verifyPreconditions();
|
||||
cleanObsoleteArtifacts();
|
||||
|
||||
await Promise.all([
|
||||
buildWebsiteManagerJs(),
|
||||
runTailwindCli({ watch: false }),
|
||||
buildGrapesHead(),
|
||||
buildGrapesBody(),
|
||||
buildPageInjectionJs(),
|
||||
buildPageInjectionCss(),
|
||||
]);
|
||||
|
||||
const totalDuration = (performance.now() - totalStart).toFixed(1);
|
||||
console.log(`\x1b[32m✨ Build finished successfully in ${totalDuration}ms.\x1b[0m\n`);
|
||||
}
|
||||
|
||||
function startWatch() {
|
||||
const tailwindProcess = runTailwindCli({ watch: true });
|
||||
|
||||
const srcDir = path.resolve(__dirname, 'src');
|
||||
console.log(`\x1b[36mWatching for changes in ${srcDir}...\x1b[0m\n`);
|
||||
|
||||
let debounceTimer = null;
|
||||
const changedPaths = new Set();
|
||||
|
||||
function triggerRebuild() {
|
||||
const paths = Array.from(changedPaths);
|
||||
changedPaths.clear();
|
||||
|
||||
const tasks = [];
|
||||
let rebuildWmJs = false;
|
||||
let rebuildPbBody = false;
|
||||
let rebuildPbHead = false;
|
||||
let rebuildInjJs = false;
|
||||
let rebuildInjCss = false;
|
||||
|
||||
for (const p of paths) {
|
||||
const normalized = p.replace(/\\/g, '/');
|
||||
if (normalized.includes('WebsiteManager/resources/assets/js/')) {
|
||||
rebuildWmJs = true;
|
||||
}
|
||||
if (normalized.includes('GrapesJS/resources/assets/js/page-injection.js')) {
|
||||
rebuildInjJs = true;
|
||||
} else if (normalized.includes('GrapesJS/resources/assets/js/')) {
|
||||
rebuildPbBody = true;
|
||||
}
|
||||
if (normalized.includes('GrapesJS/resources/assets/sass/page-injection.scss')) {
|
||||
rebuildInjCss = true;
|
||||
} else if (normalized.includes('GrapesJS/resources/assets/sass/')) {
|
||||
rebuildPbHead = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (rebuildWmJs) tasks.push(buildWebsiteManagerJs());
|
||||
if (rebuildPbBody) tasks.push(buildGrapesBody());
|
||||
if (rebuildPbHead) tasks.push(Promise.resolve(buildGrapesHead()));
|
||||
if (rebuildInjJs) tasks.push(buildPageInjectionJs());
|
||||
if (rebuildInjCss) tasks.push(Promise.resolve(buildPageInjectionCss()));
|
||||
|
||||
if (tasks.length > 0) {
|
||||
Promise.all(tasks).catch((err) => {
|
||||
console.error('\x1b[31mRebuild error:\x1b[0m', err);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const watcher = fs.watch(srcDir, { recursive: true }, (eventType, filename) => {
|
||||
if (!filename) return;
|
||||
changedPaths.add(filename);
|
||||
clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(triggerRebuild, 50);
|
||||
});
|
||||
|
||||
const cleanup = () => {
|
||||
console.log('\nStopping watchers...');
|
||||
if (tailwindProcess) tailwindProcess.kill();
|
||||
watcher.close();
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
process.on('SIGINT', cleanup);
|
||||
process.on('SIGTERM', cleanup);
|
||||
}
|
||||
|
||||
if (isWatch) {
|
||||
buildAll()
|
||||
.then(() => {
|
||||
startWatch();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('\x1b[31mBuild failed:\x1b[0m', err);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
buildAll().catch((err) => {
|
||||
console.error('\x1b[31mBuild failed:\x1b[0m', err);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user