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.

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