You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

735 rivejä
19 KiB

3 vuotta sitten
3 vuotta sitten
2 vuotta sitten
3 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
2 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
3 vuotta sitten
3 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
2 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
2 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
2 vuotta sitten
2 vuotta sitten
5 vuotta sitten
5 vuotta sitten
3 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
  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: target === 'webworker' ? { path: require.resolve('path-browserify') } : undefined,
  225. mainFields: target === 'webworker' ? ['browser', 'module', 'main'] : ['module', 'main'],
  226. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  227. },
  228. plugins: plugins,
  229. infrastructureLogging: {
  230. level: 'log', // enables logging required for problem matchers
  231. },
  232. stats: {
  233. preset: 'errors-warnings',
  234. assets: true,
  235. colors: true,
  236. env: true,
  237. errorsCount: true,
  238. warningsCount: true,
  239. timings: true,
  240. },
  241. };
  242. }
  243. /**
  244. * @param { 'production' | 'development' | 'none' } mode
  245. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } } env
  246. * @returns { WebpackConfig }
  247. */
  248. function getWebviewsConfig(mode, env) {
  249. const basePath = path.join(__dirname, 'src', 'webviews', 'apps');
  250. /** @type WebpackConfig['plugins'] | any */
  251. const plugins = [
  252. new CleanPlugin(
  253. mode === 'production'
  254. ? {
  255. cleanOnceBeforeBuildPatterns: [
  256. path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews', 'media', '**'),
  257. ],
  258. dangerouslyAllowCleanPatternsOutsideProject: true,
  259. dry: false,
  260. }
  261. : undefined,
  262. ),
  263. new ForkTsCheckerPlugin({
  264. async: false,
  265. eslint: {
  266. enabled: true,
  267. files: path.join(basePath, '**', '*.ts?(x)'),
  268. options: {
  269. // cache: true,
  270. fix: mode !== 'production',
  271. },
  272. },
  273. formatter: 'basic',
  274. typescript: {
  275. configFile: path.join(basePath, 'tsconfig.json'),
  276. },
  277. }),
  278. new MiniCssExtractPlugin({ filename: '[name].css' }),
  279. getHtmlPlugin('commitDetails', false, mode, env),
  280. getHtmlPlugin('graph', true, mode, env),
  281. getHtmlPlugin('home', false, mode, env),
  282. getHtmlPlugin('rebase', false, mode, env),
  283. getHtmlPlugin('settings', false, mode, env),
  284. getHtmlPlugin('timeline', true, mode, env),
  285. getHtmlPlugin('welcome', false, mode, env),
  286. getCspHtmlPlugin(mode, env),
  287. new InlineChunkHtmlPlugin(HtmlPlugin, mode === 'production' ? ['\\.css$'] : []),
  288. new CopyPlugin({
  289. patterns: [
  290. {
  291. from: path.posix.join(basePath.replace(/\\/g, '/'), 'media', '*.*'),
  292. to: path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews'),
  293. },
  294. {
  295. from: path.posix.join(
  296. __dirname.replace(/\\/g, '/'),
  297. 'node_modules',
  298. '@vscode',
  299. 'codicons',
  300. 'dist',
  301. 'codicon.ttf',
  302. ),
  303. to: path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews'),
  304. },
  305. ],
  306. }),
  307. ];
  308. const imageGeneratorConfig = getImageMinimizerConfig(mode, env);
  309. if (mode !== 'production') {
  310. plugins.push(
  311. new ImageMinimizerPlugin({
  312. deleteOriginalAssets: true,
  313. generator: [imageGeneratorConfig],
  314. }),
  315. );
  316. }
  317. return {
  318. name: 'webviews',
  319. context: basePath,
  320. entry: {
  321. commitDetails: './commitDetails/commitDetails.ts',
  322. graph: './plus/graph/graph.tsx',
  323. home: './home/home.ts',
  324. rebase: './rebase/rebase.ts',
  325. settings: './settings/settings.ts',
  326. timeline: './plus/timeline/timeline.ts',
  327. welcome: './welcome/welcome.ts',
  328. },
  329. mode: mode,
  330. target: 'web',
  331. devtool: mode === 'production' ? false : 'source-map',
  332. output: {
  333. filename: '[name].js',
  334. path: path.join(__dirname, 'dist', 'webviews'),
  335. publicPath: '#{root}/dist/webviews/',
  336. },
  337. optimization: {
  338. minimizer: [
  339. new TerserPlugin(
  340. env.esbuild
  341. ? {
  342. minify: TerserPlugin.esbuildMinify,
  343. terserOptions: {
  344. // @ts-ignore
  345. drop: ['debugger', 'console'],
  346. // @ts-ignore
  347. format: 'esm',
  348. minify: true,
  349. treeShaking: true,
  350. // // Keep the class names otherwise @log won't provide a useful name
  351. // keepNames: true,
  352. target: 'es2020',
  353. },
  354. }
  355. : {
  356. extractComments: false,
  357. parallel: true,
  358. // @ts-ignore
  359. terserOptions: {
  360. compress: {
  361. drop_debugger: true,
  362. drop_console: true,
  363. },
  364. ecma: 2020,
  365. // // Keep the class names otherwise @log won't provide a useful name
  366. // keep_classnames: true,
  367. module: true,
  368. },
  369. },
  370. ),
  371. new ImageMinimizerPlugin({
  372. deleteOriginalAssets: true,
  373. generator: [imageGeneratorConfig],
  374. }),
  375. new CssMinimizerPlugin({
  376. minimizerOptions: {
  377. preset: [
  378. 'cssnano-preset-advanced',
  379. { discardUnused: false, mergeIdents: false, reduceIdents: false },
  380. ],
  381. },
  382. }),
  383. ],
  384. },
  385. module: {
  386. rules: [
  387. {
  388. exclude: /\.d\.ts$/,
  389. include: path.join(__dirname, 'src'),
  390. test: /\.tsx?$/,
  391. use: env.esbuild
  392. ? {
  393. loader: 'esbuild-loader',
  394. options: {
  395. implementation: esbuild,
  396. loader: 'tsx',
  397. target: 'es2020',
  398. tsconfigRaw: resolveTSConfig(path.join(basePath, 'tsconfig.json')),
  399. },
  400. }
  401. : {
  402. loader: 'ts-loader',
  403. options: {
  404. configFile: path.join(basePath, 'tsconfig.json'),
  405. experimentalWatchApi: true,
  406. transpileOnly: true,
  407. },
  408. },
  409. },
  410. {
  411. test: /\.scss$/,
  412. use: [
  413. {
  414. loader: MiniCssExtractPlugin.loader,
  415. },
  416. {
  417. loader: 'css-loader',
  418. options: {
  419. sourceMap: mode !== 'production',
  420. url: false,
  421. },
  422. },
  423. {
  424. loader: 'sass-loader',
  425. options: {
  426. sourceMap: mode !== 'production',
  427. },
  428. },
  429. ],
  430. exclude: /node_modules/,
  431. },
  432. ],
  433. },
  434. resolve: {
  435. alias: {
  436. '@env': path.resolve(__dirname, 'src', 'env', 'browser'),
  437. },
  438. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  439. modules: [basePath, 'node_modules'],
  440. },
  441. plugins: plugins,
  442. infrastructureLogging: {
  443. level: 'log', // enables logging required for problem matchers
  444. },
  445. stats: {
  446. preset: 'errors-warnings',
  447. assets: true,
  448. colors: true,
  449. env: true,
  450. errorsCount: true,
  451. warningsCount: true,
  452. timings: true,
  453. },
  454. };
  455. }
  456. /**
  457. * @param { 'production' | 'development' | 'none' } mode
  458. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  459. * @returns { CspHtmlPlugin }
  460. */
  461. function getCspHtmlPlugin(mode, env) {
  462. const cspPlugin = new CspHtmlPlugin(
  463. {
  464. 'default-src': "'none'",
  465. 'img-src': ['#{cspSource}', 'https:', 'data:'],
  466. 'script-src':
  467. mode !== 'production'
  468. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-eval'"]
  469. : ['#{cspSource}', "'nonce-#{cspNonce}'"],
  470. 'style-src':
  471. mode === 'production'
  472. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-hashes'"]
  473. : ['#{cspSource}', "'unsafe-hashes'", "'unsafe-inline'"],
  474. 'font-src': ['#{cspSource}'],
  475. },
  476. {
  477. enabled: true,
  478. hashingMethod: 'sha256',
  479. hashEnabled: {
  480. 'script-src': true,
  481. 'style-src': mode === 'production',
  482. },
  483. nonceEnabled: {
  484. 'script-src': true,
  485. 'style-src': mode === 'production',
  486. },
  487. },
  488. );
  489. // Override the nonce creation so we can dynamically generate them at runtime
  490. // @ts-ignore
  491. cspPlugin.createNonce = () => '#{cspNonce}';
  492. return cspPlugin;
  493. }
  494. /**
  495. * @param { 'production' | 'development' | 'none' } mode
  496. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  497. * @returns { ImageMinimizerPlugin.Generator<any> }
  498. */
  499. function getImageMinimizerConfig(mode, env) {
  500. /** @type ImageMinimizerPlugin.Generator<any> */
  501. // @ts-ignore
  502. return env.useSharpForImageOptimization
  503. ? {
  504. type: 'asset',
  505. implementation: ImageMinimizerPlugin.sharpGenerate,
  506. options: {
  507. encodeOptions: {
  508. webp: {
  509. lossless: true,
  510. },
  511. },
  512. },
  513. }
  514. : {
  515. type: 'asset',
  516. implementation: ImageMinimizerPlugin.imageminGenerate,
  517. options: {
  518. plugins: [
  519. [
  520. 'imagemin-webp',
  521. {
  522. lossless: true,
  523. nearLossless: 0,
  524. quality: 100,
  525. method: mode === 'production' ? 4 : 0,
  526. },
  527. ],
  528. ],
  529. },
  530. };
  531. }
  532. /**
  533. * @param { string } name
  534. * @param { boolean } plus
  535. * @param { 'production' | 'development' | 'none' } mode
  536. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  537. * @returns { HtmlPlugin }
  538. */
  539. function getHtmlPlugin(name, plus, mode, env) {
  540. return new HtmlPlugin({
  541. template: plus ? path.join('plus', name, `${name}.html`) : path.join(name, `${name}.html`),
  542. chunks: [name],
  543. filename: path.join(__dirname, 'dist', 'webviews', `${name}.html`),
  544. inject: true,
  545. scriptLoading: 'module',
  546. inlineSource: mode === 'production' ? '.css$' : undefined,
  547. minify:
  548. mode === 'production'
  549. ? {
  550. removeComments: true,
  551. collapseWhitespace: true,
  552. removeRedundantAttributes: false,
  553. useShortDoctype: true,
  554. removeEmptyAttributes: true,
  555. removeStyleLinkTypeAttributes: true,
  556. keepClosingSlash: true,
  557. minifyCSS: true,
  558. }
  559. : false,
  560. });
  561. }
  562. class InlineChunkHtmlPlugin {
  563. constructor(htmlPlugin, patterns) {
  564. this.htmlPlugin = htmlPlugin;
  565. this.patterns = patterns;
  566. }
  567. getInlinedTag(publicPath, assets, tag) {
  568. if (
  569. (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) &&
  570. (tag.tagName !== 'link' || !(tag.attributes && tag.attributes.href))
  571. ) {
  572. return tag;
  573. }
  574. let chunkName = tag.tagName === 'link' ? tag.attributes.href : tag.attributes.src;
  575. if (publicPath) {
  576. chunkName = chunkName.replace(publicPath, '');
  577. }
  578. if (!this.patterns.some(pattern => chunkName.match(pattern))) {
  579. return tag;
  580. }
  581. const asset = assets[chunkName];
  582. if (asset == null) {
  583. return tag;
  584. }
  585. return { tagName: tag.tagName === 'link' ? 'style' : tag.tagName, innerHTML: asset.source(), closeTag: true };
  586. }
  587. apply(compiler) {
  588. let publicPath = compiler.options.output.publicPath || '';
  589. if (publicPath && !publicPath.endsWith('/')) {
  590. publicPath += '/';
  591. }
  592. compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
  593. const getInlinedTagFn = tag => this.getInlinedTag(publicPath, compilation.assets, tag);
  594. const sortFn = (a, b) => (a.tagName === 'script' ? 1 : -1) - (b.tagName === 'script' ? 1 : -1);
  595. this.htmlPlugin.getHooks(compilation).alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
  596. assets.headTags = assets.headTags.map(getInlinedTagFn).sort(sortFn);
  597. assets.bodyTags = assets.bodyTags.map(getInlinedTagFn).sort(sortFn);
  598. });
  599. });
  600. }
  601. }
  602. /**
  603. * @param { string } configFile
  604. * @returns { string }
  605. */
  606. function resolveTSConfig(configFile) {
  607. const result = spawnSync('yarn', ['tsc', `-p ${configFile}`, '--showConfig'], {
  608. cwd: __dirname,
  609. encoding: 'utf8',
  610. shell: true,
  611. });
  612. const data = result.stdout;
  613. const start = data.indexOf('{');
  614. const end = data.lastIndexOf('}') + 1;
  615. const json = JSON5.parse(data.substring(start, end));
  616. return json;
  617. }
  618. const schema = {
  619. type: 'object',
  620. properties: {
  621. config: {
  622. type: 'object',
  623. },
  624. configPath: {
  625. type: 'string',
  626. },
  627. onBefore: {
  628. instanceof: 'Function',
  629. },
  630. onComplete: {
  631. instanceof: 'Function',
  632. },
  633. },
  634. };
  635. class FantasticonPlugin {
  636. alreadyRun = false;
  637. constructor(options = {}) {
  638. this.pluginName = 'fantasticon';
  639. this.options = options;
  640. validate(
  641. // @ts-ignore
  642. schema,
  643. options,
  644. {
  645. name: this.pluginName,
  646. baseDataPath: 'options',
  647. },
  648. );
  649. }
  650. /**
  651. * @param {import("webpack").Compiler} compiler
  652. */
  653. apply(compiler) {
  654. const {
  655. config = undefined,
  656. configPath = undefined,
  657. onBefore = undefined,
  658. onComplete = undefined,
  659. } = this.options;
  660. let loadedConfig;
  661. if (configPath) {
  662. try {
  663. loadedConfig = require(path.join(__dirname, configPath));
  664. } catch (ex) {
  665. console.error(`[${this.pluginName}] Error loading configuration: ${ex}`);
  666. }
  667. }
  668. if (!loadedConfig && !config) {
  669. console.error(`[${this.pluginName}] Error loading configuration: no configuration found`);
  670. return;
  671. }
  672. const fontConfig = { ...(loadedConfig ?? {}), ...(config ?? {}) };
  673. // TODO@eamodio: Figure out how to add watching for the fontConfig.inputDir
  674. // Maybe something like: https://github.com/Fridus/webpack-watch-files-plugin
  675. /**
  676. * @this {FantasticonPlugin}
  677. * @param {import("webpack").Compiler} compiler
  678. */
  679. async function generate(compiler) {
  680. if (compiler.watchMode) {
  681. if (this.alreadyRun) return;
  682. this.alreadyRun = true;
  683. }
  684. const logger = compiler.getInfrastructureLogger(this.pluginName);
  685. logger.log(`Generating icon font...`);
  686. await onBefore?.(fontConfig);
  687. await generateFonts(fontConfig);
  688. await onComplete?.(fontConfig);
  689. logger.log(`Generated icon font`);
  690. }
  691. compiler.hooks.beforeRun.tapPromise(this.pluginName, generate.bind(this));
  692. compiler.hooks.watchRun.tapPromise(this.pluginName, generate.bind(this));
  693. }
  694. }