Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

807 rader
21 KiB

3 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
2 år sedan
5 år sedan
5 år sedan
5 år sedan
2 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
2 år sedan
2 år sedan
2 år sedan
2 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
  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('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. { discardUnused: false, mergeIdents: false, reduceIdents: false },
  437. ],
  438. },
  439. }),
  440. ]
  441. : [],
  442. splitChunks: {
  443. // Disable all non-async code splitting
  444. // chunks: () => false,
  445. cacheGroups: {
  446. default: false,
  447. vendors: false,
  448. },
  449. },
  450. },
  451. module: {
  452. rules: [
  453. {
  454. test: /\.m?js/,
  455. resolve: { fullySpecified: false },
  456. },
  457. {
  458. exclude: /\.d\.ts$/,
  459. include: path.join(__dirname, 'src'),
  460. test: /\.tsx?$/,
  461. use: env.esbuild
  462. ? {
  463. loader: 'esbuild-loader',
  464. options: {
  465. format: 'esm',
  466. implementation: esbuild,
  467. target: 'es2021',
  468. tsconfig: path.join(basePath, 'tsconfig.json'),
  469. },
  470. }
  471. : {
  472. loader: 'ts-loader',
  473. options: {
  474. configFile: path.join(basePath, 'tsconfig.json'),
  475. experimentalWatchApi: true,
  476. transpileOnly: true,
  477. },
  478. },
  479. },
  480. {
  481. test: /\.scss$/,
  482. use: [
  483. {
  484. loader: MiniCssExtractPlugin.loader,
  485. },
  486. {
  487. loader: 'css-loader',
  488. options: {
  489. sourceMap: mode !== 'production',
  490. url: false,
  491. },
  492. },
  493. {
  494. loader: 'sass-loader',
  495. options: {
  496. sourceMap: mode !== 'production',
  497. },
  498. },
  499. ],
  500. exclude: /node_modules/,
  501. },
  502. ],
  503. },
  504. resolve: {
  505. alias: {
  506. '@env': path.resolve(__dirname, 'src', 'env', 'browser'),
  507. '@microsoft/fast-foundation': path.resolve(
  508. __dirname,
  509. 'node_modules/@microsoft/fast-foundation/dist/esm/index.js',
  510. ),
  511. '@microsoft/fast-react-wrapper': path.resolve(
  512. __dirname,
  513. 'node_modules/@microsoft/fast-react-wrapper/dist/esm/index.js',
  514. ),
  515. react: path.resolve(__dirname, 'node_modules', 'react'),
  516. 'react-dom': path.resolve(__dirname, 'node_modules', 'react-dom'),
  517. tslib: path.resolve(__dirname, 'node_modules/tslib/tslib.es6.js'),
  518. },
  519. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  520. modules: [basePath, 'node_modules'],
  521. },
  522. plugins: plugins,
  523. infrastructureLogging:
  524. mode === 'production'
  525. ? undefined
  526. : {
  527. level: 'log', // enables logging required for problem matchers
  528. },
  529. stats: {
  530. preset: 'errors-warnings',
  531. assets: true,
  532. assetsSort: 'name',
  533. assetsSpace: 100,
  534. colors: true,
  535. env: true,
  536. errorsCount: true,
  537. excludeAssets: [/\.(ttf|webp)/],
  538. warningsCount: true,
  539. timings: true,
  540. },
  541. };
  542. }
  543. /**
  544. * @param { 'production' | 'development' | 'none' } mode
  545. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  546. * @returns { CspHtmlPlugin }
  547. */
  548. function getCspHtmlPlugin(mode, env) {
  549. const cspPlugin = new CspHtmlPlugin(
  550. {
  551. 'default-src': "'none'",
  552. 'img-src': ['#{cspSource}', 'https:', 'data:'],
  553. 'script-src':
  554. mode !== 'production'
  555. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-eval'"]
  556. : ['#{cspSource}', "'nonce-#{cspNonce}'"],
  557. 'style-src':
  558. mode === 'production'
  559. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-hashes'"]
  560. : ['#{cspSource}', "'unsafe-hashes'", "'unsafe-inline'"],
  561. 'font-src': ['#{cspSource}'],
  562. },
  563. {
  564. enabled: true,
  565. hashingMethod: 'sha256',
  566. hashEnabled: {
  567. 'script-src': true,
  568. 'style-src': mode === 'production',
  569. },
  570. nonceEnabled: {
  571. 'script-src': true,
  572. 'style-src': mode === 'production',
  573. },
  574. },
  575. );
  576. // Override the nonce creation so we can dynamically generate them at runtime
  577. // @ts-ignore
  578. cspPlugin.createNonce = () => '#{cspNonce}';
  579. return cspPlugin;
  580. }
  581. /**
  582. * @param { 'production' | 'development' | 'none' } mode
  583. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  584. * @returns { ImageMinimizerPlugin.Generator<any> }
  585. */
  586. function getImageMinimizerConfig(mode, env) {
  587. /** @type ImageMinimizerPlugin.Generator<any> */
  588. // @ts-ignore
  589. return env.useSharpForImageOptimization
  590. ? {
  591. type: 'asset',
  592. implementation: ImageMinimizerPlugin.sharpGenerate,
  593. options: {
  594. encodeOptions: {
  595. webp: {
  596. lossless: true,
  597. },
  598. },
  599. },
  600. }
  601. : {
  602. type: 'asset',
  603. implementation: ImageMinimizerPlugin.imageminGenerate,
  604. options: {
  605. plugins: [
  606. [
  607. 'imagemin-webp',
  608. {
  609. lossless: true,
  610. nearLossless: 0,
  611. quality: 100,
  612. method: mode === 'production' ? 4 : 0,
  613. },
  614. ],
  615. ],
  616. },
  617. };
  618. }
  619. /**
  620. * @param { string } name
  621. * @param { boolean } plus
  622. * @param { 'production' | 'development' | 'none' } mode
  623. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  624. * @returns { HtmlPlugin }
  625. */
  626. function getHtmlPlugin(name, plus, mode, env) {
  627. return new HtmlPlugin({
  628. template: plus ? path.join('plus', name, `${name}.html`) : path.join(name, `${name}.html`),
  629. chunks: [name],
  630. filename: path.join(__dirname, 'dist', 'webviews', `${name}.html`),
  631. inject: true,
  632. scriptLoading: 'module',
  633. inlineSource: mode === 'production' ? '.css$' : undefined,
  634. minify:
  635. mode === 'production'
  636. ? {
  637. removeComments: true,
  638. collapseWhitespace: true,
  639. removeRedundantAttributes: false,
  640. useShortDoctype: true,
  641. removeEmptyAttributes: true,
  642. removeStyleLinkTypeAttributes: true,
  643. keepClosingSlash: true,
  644. minifyCSS: true,
  645. }
  646. : false,
  647. });
  648. }
  649. class InlineChunkHtmlPlugin {
  650. constructor(htmlPlugin, patterns) {
  651. this.htmlPlugin = htmlPlugin;
  652. this.patterns = patterns;
  653. }
  654. getInlinedTag(publicPath, assets, tag) {
  655. if (
  656. (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) &&
  657. (tag.tagName !== 'link' || !(tag.attributes && tag.attributes.href))
  658. ) {
  659. return tag;
  660. }
  661. let chunkName = tag.tagName === 'link' ? tag.attributes.href : tag.attributes.src;
  662. if (publicPath) {
  663. chunkName = chunkName.replace(publicPath, '');
  664. }
  665. if (!this.patterns.some(pattern => chunkName.match(pattern))) {
  666. return tag;
  667. }
  668. const asset = assets[chunkName];
  669. if (asset == null) {
  670. return tag;
  671. }
  672. return { tagName: tag.tagName === 'link' ? 'style' : tag.tagName, innerHTML: asset.source(), closeTag: true };
  673. }
  674. apply(compiler) {
  675. let publicPath = compiler.options.output.publicPath || '';
  676. if (publicPath && !publicPath.endsWith('/')) {
  677. publicPath += '/';
  678. }
  679. compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
  680. const getInlinedTagFn = tag => this.getInlinedTag(publicPath, compilation.assets, tag);
  681. const sortFn = (a, b) => (a.tagName === 'script' ? 1 : -1) - (b.tagName === 'script' ? 1 : -1);
  682. this.htmlPlugin.getHooks(compilation).alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
  683. assets.headTags = assets.headTags.map(getInlinedTagFn).sort(sortFn);
  684. assets.bodyTags = assets.bodyTags.map(getInlinedTagFn).sort(sortFn);
  685. });
  686. });
  687. }
  688. }
  689. const schema = {
  690. type: 'object',
  691. properties: {
  692. config: {
  693. type: 'object',
  694. },
  695. configPath: {
  696. type: 'string',
  697. },
  698. onBefore: {
  699. instanceof: 'Function',
  700. },
  701. onComplete: {
  702. instanceof: 'Function',
  703. },
  704. },
  705. };
  706. class FantasticonPlugin {
  707. alreadyRun = false;
  708. constructor(options = {}) {
  709. this.pluginName = 'fantasticon';
  710. this.options = options;
  711. validate(
  712. // @ts-ignore
  713. schema,
  714. options,
  715. {
  716. name: this.pluginName,
  717. baseDataPath: 'options',
  718. },
  719. );
  720. }
  721. /**
  722. * @param {import("webpack").Compiler} compiler
  723. */
  724. apply(compiler) {
  725. const {
  726. config = undefined,
  727. configPath = undefined,
  728. onBefore = undefined,
  729. onComplete = undefined,
  730. } = this.options;
  731. let loadedConfig;
  732. if (configPath) {
  733. try {
  734. loadedConfig = require(path.join(__dirname, configPath));
  735. } catch (ex) {
  736. console.error(`[${this.pluginName}] Error loading configuration: ${ex}`);
  737. }
  738. }
  739. if (!loadedConfig && !config) {
  740. console.error(`[${this.pluginName}] Error loading configuration: no configuration found`);
  741. return;
  742. }
  743. const fontConfig = { ...(loadedConfig ?? {}), ...(config ?? {}) };
  744. // TODO@eamodio: Figure out how to add watching for the fontConfig.inputDir
  745. // Maybe something like: https://github.com/Fridus/webpack-watch-files-plugin
  746. /**
  747. * @this {FantasticonPlugin}
  748. * @param {import("webpack").Compiler} compiler
  749. */
  750. async function generate(compiler) {
  751. if (compiler.watchMode) {
  752. if (this.alreadyRun) return;
  753. this.alreadyRun = true;
  754. }
  755. const logger = compiler.getInfrastructureLogger(this.pluginName);
  756. logger.log(`Generating icon font...`);
  757. await onBefore?.(fontConfig);
  758. await generateFonts(fontConfig);
  759. await onComplete?.(fontConfig);
  760. logger.log(`Generated icon font`);
  761. }
  762. compiler.hooks.beforeRun.tapPromise(this.pluginName, generate.bind(this));
  763. compiler.hooks.watchRun.tapPromise(this.pluginName, generate.bind(this));
  764. }
  765. }