Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

738 рядки
19 KiB

3 роки тому
3 роки тому
2 роки тому
3 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
2 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
3 роки тому
2 роки тому
5 роки тому
2 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
2 роки тому
3 роки тому
5 роки тому
5 роки тому
5 роки тому
2 роки тому
5 роки тому
5 роки тому
5 роки тому
2 роки тому
2 роки тому
5 роки тому
5 роки тому
5 роки тому
3 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
5 роки тому
3 роки тому
3 роки тому
3 роки тому
  1. //@ts-check
  2. /** @typedef {import('webpack').Configuration} WebpackConfig **/
  3. const { spawnSync } = require('child_process');
  4. const CircularDependencyPlugin = require('circular-dependency-plugin');
  5. const { CleanWebpackPlugin: CleanPlugin } = require('clean-webpack-plugin');
  6. const CopyPlugin = require('copy-webpack-plugin');
  7. const CspHtmlPlugin = require('csp-html-webpack-plugin');
  8. const esbuild = require('esbuild');
  9. const { generateFonts } = require('fantasticon');
  10. const ForkTsCheckerPlugin = require('fork-ts-checker-webpack-plugin');
  11. const fs = require('fs');
  12. const HtmlPlugin = require('html-webpack-plugin');
  13. const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
  14. const JSON5 = require('json5');
  15. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  16. const path = require('path');
  17. const { validate } = require('schema-utils');
  18. const TerserPlugin = require('terser-webpack-plugin');
  19. const { WebpackError, webpack, optimize } = require('webpack');
  20. const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
  21. const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  22. module.exports =
  23. /**
  24. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  25. * @param {{ mode: 'production' | 'development' | 'none' | undefined }} argv
  26. * @returns { WebpackConfig[] }
  27. */
  28. function (env, argv) {
  29. const mode = argv.mode || 'none';
  30. env = {
  31. analyzeBundle: false,
  32. analyzeDeps: false,
  33. esbuild: true,
  34. useSharpForImageOptimization: true,
  35. ...env,
  36. };
  37. return [
  38. getExtensionConfig('node', mode, env),
  39. getExtensionConfig('webworker', mode, env),
  40. getWebviewsConfig(mode, env),
  41. ];
  42. };
  43. /**
  44. * @param { 'node' | 'webworker' } target
  45. * @param { 'production' | 'development' | 'none' } mode
  46. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } } env
  47. * @returns { WebpackConfig }
  48. */
  49. function getExtensionConfig(target, mode, env) {
  50. /**
  51. * @type WebpackConfig['plugins'] | any
  52. */
  53. const plugins = [
  54. new CleanPlugin({ cleanOnceBeforeBuildPatterns: ['!dist/webviews/**'] }),
  55. new ForkTsCheckerPlugin({
  56. async: false,
  57. eslint: {
  58. enabled: true,
  59. files: 'src/**/*.ts?(x)',
  60. options: {
  61. // cache: true,
  62. // cacheLocation: path.join(
  63. // __dirname,
  64. // target === 'webworker' ? '.eslintcache.browser' : '.eslintcache',
  65. // ),
  66. fix: mode !== 'production',
  67. overrideConfigFile: path.join(
  68. __dirname,
  69. target === 'webworker' ? '.eslintrc.browser.json' : '.eslintrc.json',
  70. ),
  71. },
  72. },
  73. formatter: 'basic',
  74. typescript: {
  75. configFile: path.join(__dirname, target === 'webworker' ? 'tsconfig.browser.json' : 'tsconfig.json'),
  76. },
  77. }),
  78. ];
  79. if (target === 'webworker') {
  80. plugins.push(new optimize.LimitChunkCountPlugin({ maxChunks: 1 }));
  81. } else {
  82. // Ensure that the dist folder exists otherwise the FantasticonPlugin will fail
  83. const dist = path.join(__dirname, 'dist');
  84. if (!fs.existsSync(dist)) {
  85. fs.mkdirSync(dist);
  86. }
  87. plugins.push(
  88. new FantasticonPlugin({
  89. configPath: '.fantasticonrc.js',
  90. onBefore: () =>
  91. spawnSync('yarn', ['run', 'icons:svgo'], {
  92. cwd: __dirname,
  93. encoding: 'utf8',
  94. shell: true,
  95. }),
  96. onComplete: () =>
  97. spawnSync('yarn', ['run', 'icons:apply'], {
  98. cwd: __dirname,
  99. encoding: 'utf8',
  100. shell: true,
  101. }),
  102. }),
  103. );
  104. }
  105. if (env.analyzeDeps) {
  106. plugins.push(
  107. new CircularDependencyPlugin({
  108. cwd: __dirname,
  109. exclude: /node_modules/,
  110. failOnError: false,
  111. onDetected: function ({ module: _webpackModuleRecord, paths, compilation }) {
  112. if (paths.some(p => p.includes('container.ts'))) return;
  113. // @ts-ignore
  114. compilation.warnings.push(new WebpackError(paths.join(' -> ')));
  115. },
  116. }),
  117. );
  118. }
  119. if (env.analyzeBundle) {
  120. plugins.push(new BundleAnalyzerPlugin({ analyzerPort: 'auto' }));
  121. }
  122. return {
  123. name: `extension:${target}`,
  124. entry: {
  125. extension: './src/extension.ts',
  126. },
  127. mode: mode,
  128. target: target,
  129. devtool: mode === 'production' ? false : 'source-map',
  130. output: {
  131. path: target === 'webworker' ? path.join(__dirname, 'dist', 'browser') : path.join(__dirname, 'dist'),
  132. libraryTarget: 'commonjs2',
  133. filename: 'gitlens.js',
  134. chunkFilename: 'feature-[name].js',
  135. },
  136. optimization: {
  137. minimizer: [
  138. new TerserPlugin(
  139. env.esbuild
  140. ? {
  141. minify: TerserPlugin.esbuildMinify,
  142. terserOptions: {
  143. // @ts-ignore
  144. drop: ['debugger'],
  145. format: 'cjs',
  146. minify: true,
  147. treeShaking: true,
  148. // Keep the class names otherwise @log won't provide a useful name
  149. keepNames: true,
  150. target: 'es2020',
  151. },
  152. }
  153. : {
  154. extractComments: false,
  155. parallel: true,
  156. terserOptions: {
  157. compress: {
  158. drop_debugger: true,
  159. },
  160. ecma: 2020,
  161. // Keep the class names otherwise @log won't provide a useful name
  162. keep_classnames: true,
  163. module: true,
  164. },
  165. },
  166. ),
  167. ],
  168. splitChunks:
  169. target === 'webworker'
  170. ? false
  171. : {
  172. // Disable all non-async code splitting
  173. chunks: () => false,
  174. cacheGroups: {
  175. default: false,
  176. vendors: false,
  177. },
  178. },
  179. },
  180. externals: {
  181. vscode: 'commonjs vscode',
  182. },
  183. module: {
  184. rules: [
  185. {
  186. exclude: /\.d\.ts$/,
  187. include: path.join(__dirname, 'src'),
  188. test: /\.tsx?$/,
  189. use: env.esbuild
  190. ? {
  191. loader: 'esbuild-loader',
  192. options: {
  193. implementation: esbuild,
  194. loader: 'tsx',
  195. target: ['es2020', 'chrome91', 'node14.16'],
  196. tsconfigRaw: resolveTSConfig(
  197. path.join(
  198. __dirname,
  199. target === 'webworker' ? 'tsconfig.browser.json' : 'tsconfig.json',
  200. ),
  201. ),
  202. },
  203. }
  204. : {
  205. loader: 'ts-loader',
  206. options: {
  207. configFile: path.join(
  208. __dirname,
  209. target === 'webworker' ? 'tsconfig.browser.json' : 'tsconfig.json',
  210. ),
  211. experimentalWatchApi: true,
  212. transpileOnly: true,
  213. },
  214. },
  215. },
  216. ],
  217. },
  218. resolve: {
  219. alias: {
  220. '@env': path.resolve(__dirname, 'src', 'env', target === 'webworker' ? 'browser' : target),
  221. // This dependency is very large, and isn't needed for our use-case
  222. tr46: path.resolve(__dirname, 'patches', 'tr46.js'),
  223. },
  224. fallback:
  225. target === 'webworker'
  226. ? { path: require.resolve('path-browserify'), os: require.resolve('os-browserify/browser') }
  227. : undefined,
  228. mainFields: target === 'webworker' ? ['browser', 'module', 'main'] : ['module', 'main'],
  229. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  230. },
  231. plugins: plugins,
  232. infrastructureLogging: {
  233. level: 'log', // enables logging required for problem matchers
  234. },
  235. stats: {
  236. preset: 'errors-warnings',
  237. assets: true,
  238. colors: true,
  239. env: true,
  240. errorsCount: true,
  241. warningsCount: true,
  242. timings: true,
  243. },
  244. };
  245. }
  246. /**
  247. * @param { 'production' | 'development' | 'none' } mode
  248. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } } env
  249. * @returns { WebpackConfig }
  250. */
  251. function getWebviewsConfig(mode, env) {
  252. const basePath = path.join(__dirname, 'src', 'webviews', 'apps');
  253. /** @type WebpackConfig['plugins'] | any */
  254. const plugins = [
  255. new CleanPlugin(
  256. mode === 'production'
  257. ? {
  258. cleanOnceBeforeBuildPatterns: [
  259. path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews', 'media', '**'),
  260. ],
  261. dangerouslyAllowCleanPatternsOutsideProject: true,
  262. dry: false,
  263. }
  264. : undefined,
  265. ),
  266. new ForkTsCheckerPlugin({
  267. async: false,
  268. eslint: {
  269. enabled: true,
  270. files: path.join(basePath, '**', '*.ts?(x)'),
  271. options: {
  272. // cache: true,
  273. fix: mode !== 'production',
  274. },
  275. },
  276. formatter: 'basic',
  277. typescript: {
  278. configFile: path.join(basePath, 'tsconfig.json'),
  279. },
  280. }),
  281. new MiniCssExtractPlugin({ filename: '[name].css' }),
  282. getHtmlPlugin('commitDetails', false, mode, env),
  283. getHtmlPlugin('graph', true, mode, env),
  284. getHtmlPlugin('home', false, mode, env),
  285. getHtmlPlugin('rebase', false, mode, env),
  286. getHtmlPlugin('settings', false, mode, env),
  287. getHtmlPlugin('timeline', true, mode, env),
  288. getHtmlPlugin('welcome', false, mode, env),
  289. getCspHtmlPlugin(mode, env),
  290. new InlineChunkHtmlPlugin(HtmlPlugin, mode === 'production' ? ['\\.css$'] : []),
  291. new CopyPlugin({
  292. patterns: [
  293. {
  294. from: path.posix.join(basePath.replace(/\\/g, '/'), 'media', '*.*'),
  295. to: path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews'),
  296. },
  297. {
  298. from: path.posix.join(
  299. __dirname.replace(/\\/g, '/'),
  300. 'node_modules',
  301. '@vscode',
  302. 'codicons',
  303. 'dist',
  304. 'codicon.ttf',
  305. ),
  306. to: path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews'),
  307. },
  308. ],
  309. }),
  310. ];
  311. const imageGeneratorConfig = getImageMinimizerConfig(mode, env);
  312. if (mode !== 'production') {
  313. plugins.push(
  314. new ImageMinimizerPlugin({
  315. deleteOriginalAssets: true,
  316. generator: [imageGeneratorConfig],
  317. }),
  318. );
  319. }
  320. return {
  321. name: 'webviews',
  322. context: basePath,
  323. entry: {
  324. commitDetails: './commitDetails/commitDetails.ts',
  325. graph: './plus/graph/graph.tsx',
  326. home: './home/home.ts',
  327. rebase: './rebase/rebase.ts',
  328. settings: './settings/settings.ts',
  329. timeline: './plus/timeline/timeline.ts',
  330. welcome: './welcome/welcome.ts',
  331. },
  332. mode: mode,
  333. target: 'web',
  334. devtool: mode === 'production' ? false : 'source-map',
  335. output: {
  336. filename: '[name].js',
  337. path: path.join(__dirname, 'dist', 'webviews'),
  338. publicPath: '#{root}/dist/webviews/',
  339. },
  340. optimization: {
  341. minimizer: mode === 'production' ? [
  342. new TerserPlugin(
  343. env.esbuild
  344. ? {
  345. minify: TerserPlugin.esbuildMinify,
  346. terserOptions: {
  347. // @ts-ignore
  348. drop: ['debugger', 'console'],
  349. // @ts-ignore
  350. format: 'esm',
  351. minify: true,
  352. treeShaking: true,
  353. // // Keep the class names otherwise @log won't provide a useful name
  354. // keepNames: true,
  355. target: 'es2020',
  356. },
  357. }
  358. : {
  359. extractComments: false,
  360. parallel: true,
  361. // @ts-ignore
  362. terserOptions: {
  363. compress: {
  364. drop_debugger: true,
  365. drop_console: true,
  366. },
  367. ecma: 2020,
  368. // // Keep the class names otherwise @log won't provide a useful name
  369. // keep_classnames: true,
  370. module: true,
  371. },
  372. },
  373. ),
  374. new ImageMinimizerPlugin({
  375. deleteOriginalAssets: true,
  376. generator: [imageGeneratorConfig],
  377. }),
  378. new CssMinimizerPlugin({
  379. minimizerOptions: {
  380. preset: [
  381. 'cssnano-preset-advanced',
  382. { discardUnused: false, mergeIdents: false, reduceIdents: false },
  383. ],
  384. },
  385. }),
  386. ] : [],
  387. },
  388. module: {
  389. rules: [
  390. {
  391. exclude: /\.d\.ts$/,
  392. include: path.join(__dirname, 'src'),
  393. test: /\.tsx?$/,
  394. use: env.esbuild
  395. ? {
  396. loader: 'esbuild-loader',
  397. options: {
  398. implementation: esbuild,
  399. loader: 'tsx',
  400. target: 'es2020',
  401. tsconfigRaw: resolveTSConfig(path.join(basePath, 'tsconfig.json')),
  402. },
  403. }
  404. : {
  405. loader: 'ts-loader',
  406. options: {
  407. configFile: path.join(basePath, 'tsconfig.json'),
  408. experimentalWatchApi: true,
  409. transpileOnly: true,
  410. },
  411. },
  412. },
  413. {
  414. test: /\.scss$/,
  415. use: [
  416. {
  417. loader: MiniCssExtractPlugin.loader,
  418. },
  419. {
  420. loader: 'css-loader',
  421. options: {
  422. sourceMap: mode !== 'production',
  423. url: false,
  424. },
  425. },
  426. {
  427. loader: 'sass-loader',
  428. options: {
  429. sourceMap: mode !== 'production',
  430. },
  431. },
  432. ],
  433. exclude: /node_modules/,
  434. },
  435. ],
  436. },
  437. resolve: {
  438. alias: {
  439. '@env': path.resolve(__dirname, 'src', 'env', 'browser'),
  440. },
  441. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  442. modules: [basePath, 'node_modules'],
  443. },
  444. plugins: plugins,
  445. infrastructureLogging: {
  446. level: 'log', // enables logging required for problem matchers
  447. },
  448. stats: {
  449. preset: 'errors-warnings',
  450. assets: true,
  451. colors: true,
  452. env: true,
  453. errorsCount: true,
  454. warningsCount: true,
  455. timings: true,
  456. },
  457. };
  458. }
  459. /**
  460. * @param { 'production' | 'development' | 'none' } mode
  461. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  462. * @returns { CspHtmlPlugin }
  463. */
  464. function getCspHtmlPlugin(mode, env) {
  465. const cspPlugin = new CspHtmlPlugin(
  466. {
  467. 'default-src': "'none'",
  468. 'img-src': ['#{cspSource}', 'https:', 'data:'],
  469. 'script-src':
  470. mode !== 'production'
  471. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-eval'"]
  472. : ['#{cspSource}', "'nonce-#{cspNonce}'"],
  473. 'style-src':
  474. mode === 'production'
  475. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-hashes'"]
  476. : ['#{cspSource}', "'unsafe-hashes'", "'unsafe-inline'"],
  477. 'font-src': ['#{cspSource}'],
  478. },
  479. {
  480. enabled: true,
  481. hashingMethod: 'sha256',
  482. hashEnabled: {
  483. 'script-src': true,
  484. 'style-src': mode === 'production',
  485. },
  486. nonceEnabled: {
  487. 'script-src': true,
  488. 'style-src': mode === 'production',
  489. },
  490. },
  491. );
  492. // Override the nonce creation so we can dynamically generate them at runtime
  493. // @ts-ignore
  494. cspPlugin.createNonce = () => '#{cspNonce}';
  495. return cspPlugin;
  496. }
  497. /**
  498. * @param { 'production' | 'development' | 'none' } mode
  499. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  500. * @returns { ImageMinimizerPlugin.Generator<any> }
  501. */
  502. function getImageMinimizerConfig(mode, env) {
  503. /** @type ImageMinimizerPlugin.Generator<any> */
  504. // @ts-ignore
  505. return env.useSharpForImageOptimization
  506. ? {
  507. type: 'asset',
  508. implementation: ImageMinimizerPlugin.sharpGenerate,
  509. options: {
  510. encodeOptions: {
  511. webp: {
  512. lossless: true,
  513. },
  514. },
  515. },
  516. }
  517. : {
  518. type: 'asset',
  519. implementation: ImageMinimizerPlugin.imageminGenerate,
  520. options: {
  521. plugins: [
  522. [
  523. 'imagemin-webp',
  524. {
  525. lossless: true,
  526. nearLossless: 0,
  527. quality: 100,
  528. method: mode === 'production' ? 4 : 0,
  529. },
  530. ],
  531. ],
  532. },
  533. };
  534. }
  535. /**
  536. * @param { string } name
  537. * @param { boolean } plus
  538. * @param { 'production' | 'development' | 'none' } mode
  539. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  540. * @returns { HtmlPlugin }
  541. */
  542. function getHtmlPlugin(name, plus, mode, env) {
  543. return new HtmlPlugin({
  544. template: plus ? path.join('plus', name, `${name}.html`) : path.join(name, `${name}.html`),
  545. chunks: [name],
  546. filename: path.join(__dirname, 'dist', 'webviews', `${name}.html`),
  547. inject: true,
  548. scriptLoading: 'module',
  549. inlineSource: mode === 'production' ? '.css$' : undefined,
  550. minify:
  551. mode === 'production'
  552. ? {
  553. removeComments: true,
  554. collapseWhitespace: true,
  555. removeRedundantAttributes: false,
  556. useShortDoctype: true,
  557. removeEmptyAttributes: true,
  558. removeStyleLinkTypeAttributes: true,
  559. keepClosingSlash: true,
  560. minifyCSS: true,
  561. }
  562. : false,
  563. });
  564. }
  565. class InlineChunkHtmlPlugin {
  566. constructor(htmlPlugin, patterns) {
  567. this.htmlPlugin = htmlPlugin;
  568. this.patterns = patterns;
  569. }
  570. getInlinedTag(publicPath, assets, tag) {
  571. if (
  572. (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) &&
  573. (tag.tagName !== 'link' || !(tag.attributes && tag.attributes.href))
  574. ) {
  575. return tag;
  576. }
  577. let chunkName = tag.tagName === 'link' ? tag.attributes.href : tag.attributes.src;
  578. if (publicPath) {
  579. chunkName = chunkName.replace(publicPath, '');
  580. }
  581. if (!this.patterns.some(pattern => chunkName.match(pattern))) {
  582. return tag;
  583. }
  584. const asset = assets[chunkName];
  585. if (asset == null) {
  586. return tag;
  587. }
  588. return { tagName: tag.tagName === 'link' ? 'style' : tag.tagName, innerHTML: asset.source(), closeTag: true };
  589. }
  590. apply(compiler) {
  591. let publicPath = compiler.options.output.publicPath || '';
  592. if (publicPath && !publicPath.endsWith('/')) {
  593. publicPath += '/';
  594. }
  595. compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
  596. const getInlinedTagFn = tag => this.getInlinedTag(publicPath, compilation.assets, tag);
  597. const sortFn = (a, b) => (a.tagName === 'script' ? 1 : -1) - (b.tagName === 'script' ? 1 : -1);
  598. this.htmlPlugin.getHooks(compilation).alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
  599. assets.headTags = assets.headTags.map(getInlinedTagFn).sort(sortFn);
  600. assets.bodyTags = assets.bodyTags.map(getInlinedTagFn).sort(sortFn);
  601. });
  602. });
  603. }
  604. }
  605. /**
  606. * @param { string } configFile
  607. * @returns { string }
  608. */
  609. function resolveTSConfig(configFile) {
  610. const result = spawnSync('yarn', ['tsc', `-p ${configFile}`, '--showConfig'], {
  611. cwd: __dirname,
  612. encoding: 'utf8',
  613. shell: true,
  614. });
  615. const data = result.stdout;
  616. const start = data.indexOf('{');
  617. const end = data.lastIndexOf('}') + 1;
  618. const json = JSON5.parse(data.substring(start, end));
  619. return json;
  620. }
  621. const schema = {
  622. type: 'object',
  623. properties: {
  624. config: {
  625. type: 'object',
  626. },
  627. configPath: {
  628. type: 'string',
  629. },
  630. onBefore: {
  631. instanceof: 'Function',
  632. },
  633. onComplete: {
  634. instanceof: 'Function',
  635. },
  636. },
  637. };
  638. class FantasticonPlugin {
  639. alreadyRun = false;
  640. constructor(options = {}) {
  641. this.pluginName = 'fantasticon';
  642. this.options = options;
  643. validate(
  644. // @ts-ignore
  645. schema,
  646. options,
  647. {
  648. name: this.pluginName,
  649. baseDataPath: 'options',
  650. },
  651. );
  652. }
  653. /**
  654. * @param {import("webpack").Compiler} compiler
  655. */
  656. apply(compiler) {
  657. const {
  658. config = undefined,
  659. configPath = undefined,
  660. onBefore = undefined,
  661. onComplete = undefined,
  662. } = this.options;
  663. let loadedConfig;
  664. if (configPath) {
  665. try {
  666. loadedConfig = require(path.join(__dirname, configPath));
  667. } catch (ex) {
  668. console.error(`[${this.pluginName}] Error loading configuration: ${ex}`);
  669. }
  670. }
  671. if (!loadedConfig && !config) {
  672. console.error(`[${this.pluginName}] Error loading configuration: no configuration found`);
  673. return;
  674. }
  675. const fontConfig = { ...(loadedConfig ?? {}), ...(config ?? {}) };
  676. // TODO@eamodio: Figure out how to add watching for the fontConfig.inputDir
  677. // Maybe something like: https://github.com/Fridus/webpack-watch-files-plugin
  678. /**
  679. * @this {FantasticonPlugin}
  680. * @param {import("webpack").Compiler} compiler
  681. */
  682. async function generate(compiler) {
  683. if (compiler.watchMode) {
  684. if (this.alreadyRun) return;
  685. this.alreadyRun = true;
  686. }
  687. const logger = compiler.getInfrastructureLogger(this.pluginName);
  688. logger.log(`Generating icon font...`);
  689. await onBefore?.(fontConfig);
  690. await generateFonts(fontConfig);
  691. await onComplete?.(fontConfig);
  692. logger.log(`Generated icon font`);
  693. }
  694. compiler.hooks.beforeRun.tapPromise(this.pluginName, generate.bind(this));
  695. compiler.hooks.watchRun.tapPromise(this.pluginName, generate.bind(this));
  696. }
  697. }