Skip to content

Simplify our building packages tool (drop Rollup for tsdown) #2935

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 61 additions & 89 deletions bin/build_package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import { parseArgs } from 'node:util';
import * as LightningCSS from 'lightningcss';
import * as rollup from 'rollup';
import { globSync } from 'tinyglobby';
import { getRollupConfiguration } from './rollup.ts';
import { build } from 'tsdown';

const args = parseArgs({
allowPositionals: true,
Expand All @@ -34,7 +33,7 @@ async function main() {
process.exit(1);
}

const packageData = await import(path.join(packageRoot, 'package.json'), {with: { type: 'json'}});
const packageData = await import(path.join(packageRoot, 'package.json'), { with: { type: 'json' } });
const packageName = packageData.name;
const srcDir = path.join(packageRoot, 'src');
const distDir = path.join(packageRoot, 'dist');
Expand All @@ -44,107 +43,80 @@ async function main() {
process.exit(1);
}

if (fs.existsSync(distDir)) {
console.log(`Cleaning up the "${distDir}" directory...`);
await fs.promises.rm(distDir, { recursive: true });
await fs.promises.mkdir(distDir);
}

const inputScriptFiles = [
const inputFiles = [
...globSync(path.join(srcDir, '*controller.ts')),
...(['@symfony/ux-react', '@symfony/ux-vue', '@symfony/ux-svelte'].includes(packageName)
? [path.join(srcDir, 'loader.ts'), path.join(srcDir, 'components.ts')]
: []),
...(packageName === '@symfony/stimulus-bundle'
? [path.join(srcDir, 'loader.ts'), path.join(srcDir, 'controllers.ts')]
: []),
...(packageData?.config?.css_source ? [packageData.config.css_source] : []),
];

const inputStyleFile = packageData.config?.css_source;
const buildCss = async () => {
if (!inputStyleFile) {
return;
}
const inputStyleFileDist = path.resolve(distDir, `${path.basename(inputStyleFile, '.css')}.min.css`);

console.log('Minifying CSS...');
const css = await fs.promises.readFile(inputStyleFile, 'utf-8');
const { code: minified } = LightningCSS.transform({
filename: path.basename(inputStyleFile, '.css'),
code: Buffer.from(css),
minify: true,
sourceMap: false, // TODO: Maybe we can add source maps later? :)
});
await fs.promises.writeFile(inputStyleFileDist, minified);
};
const external = [];

if (inputScriptFiles.length === 0) {
console.error(
`No input files found for package "${packageName}" (directory "${packageRoot}").\nEnsure you have at least a file matching the pattern "src/*_controller.ts", or manually specify input files in "${import.meta.filename}" file.`
);
process.exit(1);
}
inputFiles.forEach((file) => {
// custom handling for StimulusBundle
if (file.includes('StimulusBundle/assets/src/loader.ts')) {
external.push('./controllers.js');
}

const rollupConfig = getRollupConfiguration({
packageRoot,
inputFiles: inputScriptFiles,
isWatch,
additionalPlugins: [
...(isWatch && inputStyleFile
? [
{
name: 'watcher',
buildStart(this: rollup.PluginContext) {
this.addWatchFile(inputStyleFile);
},
},
]
: []),
],
// React, Vue
if (file.includes('assets/src/loader.ts')) {
external.push('./components.js');
}
});

if (isWatch) {
console.log(
`Watching for JavaScript${inputStyleFile ? ' and CSS' : ''} files modifications in "${srcDir}" directory...`
);

const watcher = rollup.watch(rollupConfig);
watcher.on('event', (event) => {
if (event.code === 'ERROR') {
console.error('Error during build:', event.error);
}

if ((event.code === 'BUNDLE_END' || event.code === 'ERROR') && event.result) {
event.result.close();
}
});
watcher.on('change', async (id, { event }) => {
if (event === 'update') {
console.log('Files were modified, rebuilding...');
}

if (inputStyleFile && id === inputStyleFile) {
await buildCss();
build({
entry: inputFiles,
outDir: distDir,
clean: true,
outputOptions: {
cssEntryFileNames: '[name].min.css',
},
external,
format: 'esm',
platform: 'browser',
tsconfig: path.join(import.meta.dirname, '../tsconfig.packages.json'),
// The target should be kept in sync with `tsconfig.packages.json` file.
// In the future, I hope the target will be read from the `tsconfig.packages.json` file, but for now we need to specify it manually.
target: 'es2022',
watch: isWatch,
plugins: [
// Since minifying files is not configurable per file, we need to use a custom plugin to handle CSS minification.
{
name: 'minimize-css',
transform: {
filter: {
id: /\.css$/,
},
handler (code, id) {
const { code: minifiedCode } = LightningCSS.transform({
filename: path.basename(id),
code: Buffer.from(code),
minify: true,
sourceMap: false,
});

return { code: minifiedCode.toString(), map: null };
}
},
},
],
hooks: {
async 'build:done'() {
// TODO: Idk why, but when we build a CSS file (e.g. `style.css`), it also generate an empty JS file (e.g. `style.js`).
if (packageData?.config?.css_source) {
const unwantedJsFile = path.join(distDir, path.basename(packageData.config.css_source, '.css') + '.js');
await fs.promises.rm(unwantedJsFile, { force: true });
}
}
});
} else {
console.log(`Building JavaScript files from ${packageName} package...`);
const start = Date.now();

if (typeof rollupConfig.output === 'undefined' || Array.isArray(rollupConfig.output)) {
console.error(
`The rollup configuration for package "${packageName}" does not contain a valid output configuration.`
);
process.exit(1);
}

const bundle = await rollup.rollup(rollupConfig);
await bundle.write(rollupConfig.output);

await buildCss();

console.log(`Done in ${((Date.now() - start) / 1000).toFixed(3)} seconds.`);
}
}).catch((error) => {
console.error('Error during build:', error);
process.exit(1);
});
}

main();
143 changes: 0 additions & 143 deletions bin/rollup.ts

This file was deleted.

6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,14 @@
},
"devDependencies": {
"@biomejs/biome": "^2.0.4",
"@rollup/plugin-commonjs": "^28.0.6",
"@rollup/plugin-node-resolve": "^16.0.1",
"@rollup/plugin-typescript": "^12.1.4",
"@oxc-project/runtime": "^0.77.3",
"@testing-library/dom": "catalog:",
"@testing-library/jest-dom": "catalog:",
"@types/node": "^22.6.0",
"lightningcss": "^1.28.2",
"playwright": "^1.47.0",
"rollup": "^4.44.1",
"tinyglobby": "^0.2.14",
"tsdown": "^0.12.9",
"vitest": "catalog:"
},
"version": "2.27.0"
Expand Down
Loading
Loading