build.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { readFile } from 'fs/promises';
  2. import { globbyStream } from 'globby';
  3. import { parseArgs } from 'util';
  4. import { build, createServer, InlineConfig } from 'vite';
  5. import { _userscript } from './_userscript.js';
  6. const pkg = JSON.parse(await readFile('package.json', 'utf8'));
  7. const args = parseArgs({
  8. options: {
  9. production: {
  10. type: 'boolean',
  11. default: false
  12. }
  13. }
  14. });
  15. const server = await createServer({
  16. plugins: [
  17. {
  18. name: 'rewrite',
  19. configureServer(server) {
  20. server.middlewares.use(async (req, res, next) => {
  21. req.url = '/out' + req.url;
  22. next();
  23. });
  24. }
  25. }
  26. ],
  27. optimizeDeps: {
  28. disabled: true
  29. }
  30. });
  31. if (!args.values.production) {
  32. await server.listen();
  33. await server.printUrls();
  34. }
  35. const entries: string[] = [];
  36. for await (const path of await globbyStream('src/**/main.ts')) {
  37. const code = await readFile(path, { encoding: 'utf8' });
  38. if (!code.startsWith('// ==UserScript==')) continue;
  39. entries.push(path.toString());
  40. }
  41. const configs = entries.map<InlineConfig>(entry => ({
  42. mode: args.values.production ? 'production' : 'development',
  43. plugins: [
  44. _userscript({
  45. entry: entry,
  46. format: 'umd',
  47. port: server.config.server.port,
  48. cdn: args.values.production ? pkg.homepage : '',
  49. })
  50. ],
  51. build: {
  52. watch: args.values.production ? undefined : {},
  53. outDir: args.values.production ? 'dist/' : 'out/'
  54. }
  55. }));
  56. await Promise.all(configs.map(build));
  57. if (args.values.production) await server.close();