Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

812 righe
21 KiB

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