summaryrefslogtreecommitdiff
path: root/esbuild.config.js
blob: 1bee10c95e76862f9cab159ab15e5822c422157a (plain) (blame)
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
const esbuild = require('esbuild');
const fs = require('fs-extra');
const path = require('path');

const production = process.env.NODE_ENV === 'production';

async function buildJS() {
  await esbuild.build({
    entryPoints: ['src/js/script.js'],
    bundle: true,
    minify: production,
    sourcemap: true,
    target: 'es2020',
    outfile: 'dist/bundle.js',
  });
}

async function buildCSS() {
  await esbuild.build({
    entryPoints: ['src/css/style.css'],
    bundle: true,
    minify: production,
    sourcemap: true,
    loader: {
      '.css': 'css',
      '.woff2': 'file',
      '.png': 'file',
      '.svg': 'file',
    },
    outfile: 'dist/bundle.css',
  });
}

async function copyAssets() {
  await fs.copy('src/assets', 'dist', {
    overwrite: true,
  });
}

async function processHTML() {
  let html = await fs.readFile('src/index.html', 'utf8');

  const host = process.env.HOST || '';
  const cleanHost = host.replace(/\/$/, '');

  if (cleanHost) {
    html = html.replace(/href="\/bundle\./g, `href="${cleanHost}/bundle.`);
    html = html.replace(/src="\/bundle\./g, `src="${cleanHost}/bundle.`);
    html = html.replace(/href="\/img\//g, `href="${cleanHost}/img/`);
    html = html.replace(/src="\/oneko\//g, `src="${cleanHost}/oneko/`);
  }

  await fs.writeFile('dist/index.html', html);
}

async function clean() {
  await fs.remove('dist');
  await fs.ensureDir('dist');
}

async function build() {
  try {
    await clean();
    await Promise.all([
      buildJS(),
      buildCSS(),
      copyAssets(),
    ]);
    await processHTML();
  } catch (err) {
    process.exit(1);
  }
}

build();