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.

740 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; squoosh?: 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. squoosh: 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; squoosh?: 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; squoosh?: 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. fallback: {
  441. crypto: require.resolve('crypto-browserify'),
  442. stream: require.resolve('stream-browserify'),
  443. },
  444. },
  445. plugins: plugins,
  446. infrastructureLogging: {
  447. level: 'log', // enables logging required for problem matchers
  448. },
  449. stats: {
  450. preset: 'errors-warnings',
  451. assets: true,
  452. colors: true,
  453. env: true,
  454. errorsCount: true,
  455. warningsCount: true,
  456. timings: true,
  457. },
  458. };
  459. }
  460. /**
  461. * @param { 'production' | 'development' | 'none' } mode
  462. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; squoosh?: boolean } | undefined } env
  463. * @returns { CspHtmlPlugin }
  464. */
  465. function getCspHtmlPlugin(mode, env) {
  466. const cspPlugin = new CspHtmlPlugin(
  467. {
  468. 'default-src': "'none'",
  469. 'img-src': ['#{cspSource}', 'https:', 'data:'],
  470. 'script-src':
  471. mode !== 'production'
  472. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-eval'"]
  473. : ['#{cspSource}', "'nonce-#{cspNonce}'"],
  474. 'style-src':
  475. mode === 'production'
  476. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-hashes'"]
  477. : ['#{cspSource}', "'unsafe-hashes'", "'unsafe-inline'"],
  478. 'font-src': ['#{cspSource}'],
  479. },
  480. {
  481. enabled: true,
  482. hashingMethod: 'sha256',
  483. hashEnabled: {
  484. 'script-src': true,
  485. 'style-src': mode === 'production',
  486. },
  487. nonceEnabled: {
  488. 'script-src': true,
  489. 'style-src': mode === 'production',
  490. },
  491. },
  492. );
  493. // Override the nonce creation so we can dynamically generate them at runtime
  494. // @ts-ignore
  495. cspPlugin.createNonce = () => '#{cspNonce}';
  496. return cspPlugin;
  497. }
  498. /**
  499. * @param { 'production' | 'development' | 'none' } mode
  500. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; squoosh?: boolean } | undefined } env
  501. * @returns { ImageMinimizerPlugin.Generator<any> }
  502. */
  503. function getImageMinimizerConfig(mode, env) {
  504. /** @type ImageMinimizerPlugin.Generator<any> */
  505. // @ts-ignore
  506. return env.squoosh
  507. ? {
  508. type: 'asset',
  509. implementation: ImageMinimizerPlugin.squooshGenerate,
  510. options: {
  511. encodeOptions: {
  512. webp: {
  513. // quality: 90,
  514. lossless: 1,
  515. },
  516. },
  517. },
  518. }
  519. : {
  520. type: 'asset',
  521. implementation: ImageMinimizerPlugin.imageminGenerate,
  522. options: {
  523. plugins: [
  524. [
  525. 'imagemin-webp',
  526. {
  527. lossless: true,
  528. nearLossless: 0,
  529. quality: 100,
  530. method: mode === 'production' ? 4 : 0,
  531. },
  532. ],
  533. ],
  534. },
  535. };
  536. }
  537. /**
  538. * @param { string } name
  539. * @param { boolean } plus
  540. * @param { 'production' | 'development' | 'none' } mode
  541. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; squoosh?: boolean } | undefined } env
  542. * @returns { HtmlPlugin }
  543. */
  544. function getHtmlPlugin(name, plus, mode, env) {
  545. return new HtmlPlugin({
  546. template: plus ? path.join('plus', name, `${name}.html`) : path.join(name, `${name}.html`),
  547. chunks: [name],
  548. filename: path.join(__dirname, 'dist', 'webviews', `${name}.html`),
  549. inject: true,
  550. scriptLoading: 'module',
  551. inlineSource: mode === 'production' ? '.css$' : undefined,
  552. minify:
  553. mode === 'production'
  554. ? {
  555. removeComments: true,
  556. collapseWhitespace: true,
  557. removeRedundantAttributes: false,
  558. useShortDoctype: true,
  559. removeEmptyAttributes: true,
  560. removeStyleLinkTypeAttributes: true,
  561. keepClosingSlash: true,
  562. minifyCSS: true,
  563. }
  564. : false,
  565. });
  566. }
  567. class InlineChunkHtmlPlugin {
  568. constructor(htmlPlugin, patterns) {
  569. this.htmlPlugin = htmlPlugin;
  570. this.patterns = patterns;
  571. }
  572. getInlinedTag(publicPath, assets, tag) {
  573. if (
  574. (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) &&
  575. (tag.tagName !== 'link' || !(tag.attributes && tag.attributes.href))
  576. ) {
  577. return tag;
  578. }
  579. let chunkName = tag.tagName === 'link' ? tag.attributes.href : tag.attributes.src;
  580. if (publicPath) {
  581. chunkName = chunkName.replace(publicPath, '');
  582. }
  583. if (!this.patterns.some(pattern => chunkName.match(pattern))) {
  584. return tag;
  585. }
  586. const asset = assets[chunkName];
  587. if (asset == null) {
  588. return tag;
  589. }
  590. return { tagName: tag.tagName === 'link' ? 'style' : tag.tagName, innerHTML: asset.source(), closeTag: true };
  591. }
  592. apply(compiler) {
  593. let publicPath = compiler.options.output.publicPath || '';
  594. if (publicPath && !publicPath.endsWith('/')) {
  595. publicPath += '/';
  596. }
  597. compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
  598. const getInlinedTagFn = tag => this.getInlinedTag(publicPath, compilation.assets, tag);
  599. const sortFn = (a, b) => (a.tagName === 'script' ? 1 : -1) - (b.tagName === 'script' ? 1 : -1);
  600. this.htmlPlugin.getHooks(compilation).alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
  601. assets.headTags = assets.headTags.map(getInlinedTagFn).sort(sortFn);
  602. assets.bodyTags = assets.bodyTags.map(getInlinedTagFn).sort(sortFn);
  603. });
  604. });
  605. }
  606. }
  607. /**
  608. * @param { string } configFile
  609. * @returns { string }
  610. */
  611. function resolveTSConfig(configFile) {
  612. const result = spawnSync('yarn', ['tsc', `-p ${configFile}`, '--showConfig'], {
  613. cwd: __dirname,
  614. encoding: 'utf8',
  615. shell: true,
  616. });
  617. const data = result.stdout;
  618. const start = data.indexOf('{');
  619. const end = data.lastIndexOf('}') + 1;
  620. const json = JSON5.parse(data.substring(start, end));
  621. return json;
  622. }
  623. const schema = {
  624. type: 'object',
  625. properties: {
  626. config: {
  627. type: 'object',
  628. },
  629. configPath: {
  630. type: 'string',
  631. },
  632. onBefore: {
  633. instanceof: 'Function',
  634. },
  635. onComplete: {
  636. instanceof: 'Function',
  637. },
  638. },
  639. };
  640. class FantasticonPlugin {
  641. alreadyRun = false;
  642. constructor(options = {}) {
  643. this.pluginName = 'fantasticon';
  644. this.options = options;
  645. validate(
  646. // @ts-ignore
  647. schema,
  648. options,
  649. {
  650. name: this.pluginName,
  651. baseDataPath: 'options',
  652. },
  653. );
  654. }
  655. /**
  656. * @param {import("webpack").Compiler} compiler
  657. */
  658. apply(compiler) {
  659. const {
  660. config = undefined,
  661. configPath = undefined,
  662. onBefore = undefined,
  663. onComplete = undefined,
  664. } = this.options;
  665. let loadedConfig;
  666. if (configPath) {
  667. try {
  668. loadedConfig = require(path.join(__dirname, configPath));
  669. } catch (ex) {
  670. console.error(`[${this.pluginName}] Error loading configuration: ${ex}`);
  671. }
  672. }
  673. if (!loadedConfig && !config) {
  674. console.error(`[${this.pluginName}] Error loading configuration: no configuration found`);
  675. return;
  676. }
  677. const fontConfig = { ...(loadedConfig ?? {}), ...(config ?? {}) };
  678. // TODO@eamodio: Figure out how to add watching for the fontConfig.inputDir
  679. // Maybe something like: https://github.com/Fridus/webpack-watch-files-plugin
  680. /**
  681. * @this {FantasticonPlugin}
  682. * @param {import("webpack").Compiler} compiler
  683. */
  684. async function generate(compiler) {
  685. if (compiler.watchMode) {
  686. if (this.alreadyRun) return;
  687. this.alreadyRun = true;
  688. }
  689. const logger = compiler.getInfrastructureLogger(this.pluginName);
  690. logger.log(`Generating icon font...`);
  691. await onBefore?.(fontConfig);
  692. await generateFonts(fontConfig);
  693. await onComplete?.(fontConfig);
  694. logger.log(`Generated icon font`);
  695. }
  696. compiler.hooks.beforeRun.tapPromise(this.pluginName, generate.bind(this));
  697. compiler.hooks.watchRun.tapPromise(this.pluginName, generate.bind(this));
  698. }
  699. }