universo-platform-2d

Форк
0
152 строки · 4.5 Кб
1
import { execSync } from 'node:child_process';
2
import { join, resolve } from 'node:path';
3

4
import type { BuildFlags } from '@affine/cli/config';
5
import { Repository } from '@napi-rs/simple-git';
6
import HTMLPlugin from 'html-webpack-plugin';
7
import { once } from 'lodash-es';
8
import type { Compiler } from 'webpack';
9
import webpack from 'webpack';
10
import { merge } from 'webpack-merge';
11

12
import {
13
  createConfiguration,
14
  getPublicPath,
15
  rootPath,
16
  workspaceRoot,
17
} from './config.js';
18
import { getBuildConfig } from './runtime-config.js';
19

20
const DESCRIPTION = `There can be more than Notion and Miro. AFFiNE is a next-gen knowledge base that brings planning, sorting and creating all together.`;
21

22
const gitShortHash = once(() => {
23
  const { GITHUB_SHA } = process.env;
24
  if (GITHUB_SHA) {
25
    return GITHUB_SHA.substring(0, 9);
26
  }
27
  const repo = new Repository(workspaceRoot);
28
  const shortSha = repo.head().target()?.substring(0, 9);
29
  if (shortSha) {
30
    return shortSha;
31
  }
32
  const sha = execSync(`git rev-parse --short HEAD`, {
33
    encoding: 'utf-8',
34
  }).trim();
35
  return sha;
36
});
37

38
export function createWebpackConfig(cwd: string, flags: BuildFlags) {
39
  console.log('build flags', flags);
40
  const runtimeConfig = getBuildConfig(flags);
41
  console.log('BUILD_CONFIG', runtimeConfig);
42
  const config = createConfiguration(cwd, flags, runtimeConfig);
43
  const entry =
44
    typeof flags.entry === 'string' || !flags.entry
45
      ? {
46
          app: flags.entry ?? resolve(cwd, 'src/index.tsx'),
47
        }
48
      : flags.entry;
49

50
  const publicPath = getPublicPath(flags);
51
  const cdnOrigin = publicPath.startsWith('/')
52
    ? undefined
53
    : new URL(publicPath).origin;
54

55
  const templateParams = {
56
    GIT_SHORT_SHA: gitShortHash(),
57
    DESCRIPTION,
58
    PRECONNECT: cdnOrigin
59
      ? `<link rel="preconnect" href="${cdnOrigin}" />`
60
      : '',
61
    VIEWPORT_FIT: flags.distribution === 'mobile' ? 'cover' : 'auto',
62
  };
63

64
  const createHTMLPlugins = (entryName: string) => {
65
    const htmlPluginOptions = {
66
      template: join(rootPath, 'webpack', 'template.html'),
67
      inject: 'body',
68
      filename: 'index.html',
69
      minify: false,
70
      templateParameters: templateParams,
71
      chunks: [entryName],
72
    } satisfies HTMLPlugin.Options;
73

74
    if (entryName === 'app') {
75
      return [
76
        {
77
          apply(compiler: Compiler) {
78
            compiler.hooks.compilation.tap(
79
              'assets-manifest-plugin',
80
              compilation => {
81
                HTMLPlugin.getHooks(compilation).beforeAssetTagGeneration.tap(
82
                  'assets-manifest-plugin',
83
                  arg => {
84
                    if (!compilation.getAsset('assets-manifest.json')) {
85
                      compilation.emitAsset(
86
                        `assets-manifest.json`,
87
                        new webpack.sources.RawSource(
88
                          JSON.stringify(
89
                            {
90
                              ...arg.assets,
91
                              js: arg.assets.js.map(file =>
92
                                file.substring(arg.assets.publicPath.length)
93
                              ),
94
                              css: arg.assets.css.map(file =>
95
                                file.substring(arg.assets.publicPath.length)
96
                              ),
97
                              gitHash: templateParams.GIT_SHORT_SHA,
98
                              description: templateParams.DESCRIPTION,
99
                            },
100
                            null,
101
                            2
102
                          )
103
                        ),
104
                        {
105
                          immutable: false,
106
                        }
107
                      );
108
                    }
109

110
                    return arg;
111
                  }
112
                );
113
              }
114
            );
115
          },
116
        },
117
        new HTMLPlugin({
118
          ...htmlPluginOptions,
119
          publicPath,
120
          meta: {
121
            'env:publicPath': publicPath,
122
          },
123
        }),
124
        // selfhost html
125
        new HTMLPlugin({
126
          ...htmlPluginOptions,
127
          meta: {
128
            'env:isSelfHosted': 'true',
129
            'env:publicPath': '/',
130
          },
131
          filename: 'selfhost.html',
132
          templateParameters: {
133
            ...htmlPluginOptions.templateParameters,
134
            PRECONNECT: '',
135
          },
136
        }),
137
      ];
138
    } else {
139
      return [
140
        new HTMLPlugin({
141
          ...htmlPluginOptions,
142
          filename: `${entryName}.html`,
143
        }),
144
      ];
145
    }
146
  };
147

148
  return merge(config, {
149
    entry,
150
    plugins: Object.keys(entry).map(createHTMLPlugins).flat(),
151
  });
152
}
153

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.