Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

814 строки
22 KiB

3 лет назад
3 лет назад
3 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
3 лет назад
5 лет назад
2 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
2 лет назад
1 год назад
3 лет назад
5 лет назад
5 лет назад
5 лет назад
2 лет назад
1 год назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
5 лет назад
2 лет назад
5 лет назад
5 лет назад
3 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
5 лет назад
1 год назад
1 год назад
5 лет назад
5 лет назад
5 лет назад
  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. getHtmlPlugin('patchDetails', true, mode, env),
  320. getCspHtmlPlugin(mode, env),
  321. new InlineChunkHtmlPlugin(HtmlPlugin, mode === 'production' ? ['\\.css$'] : []),
  322. new CopyPlugin({
  323. patterns: [
  324. {
  325. from: path.posix.join(basePath.replace(/\\/g, '/'), 'media', '*.*'),
  326. to: path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews'),
  327. },
  328. {
  329. from: path.posix.join(
  330. __dirname.replace(/\\/g, '/'),
  331. 'node_modules',
  332. '@vscode',
  333. 'codicons',
  334. 'dist',
  335. 'codicon.ttf',
  336. ),
  337. to: path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews'),
  338. },
  339. ],
  340. }),
  341. ];
  342. const imageGeneratorConfig = getImageMinimizerConfig(mode, env);
  343. if (mode !== 'production') {
  344. plugins.push(
  345. new ImageMinimizerPlugin({
  346. deleteOriginalAssets: true,
  347. generator: [imageGeneratorConfig],
  348. }),
  349. );
  350. }
  351. if (env.analyzeBundle) {
  352. const out = path.join(__dirname, 'out');
  353. if (!fs.existsSync(out)) {
  354. fs.mkdirSync(out);
  355. }
  356. plugins.push(
  357. new BundleAnalyzerPlugin({
  358. analyzerMode: 'static',
  359. generateStatsFile: true,
  360. openAnalyzer: false,
  361. reportFilename: path.join(out, 'webview-bundle-report.html'),
  362. statsFilename: path.join(out, 'stats.json'),
  363. }),
  364. );
  365. }
  366. return {
  367. name: 'webviews',
  368. context: basePath,
  369. entry: {
  370. commitDetails: './commitDetails/commitDetails.ts',
  371. graph: './plus/graph/graph.tsx',
  372. home: './home/home.ts',
  373. rebase: './rebase/rebase.ts',
  374. settings: './settings/settings.ts',
  375. timeline: './plus/timeline/timeline.ts',
  376. welcome: './welcome/welcome.ts',
  377. focus: './plus/focus/focus.ts',
  378. account: './plus/account/account.ts',
  379. patchDetails: './plus/patchDetails/patchDetails.ts',
  380. },
  381. mode: mode,
  382. target: 'web',
  383. devtool: mode === 'production' ? false : 'source-map',
  384. output: {
  385. chunkFilename: 'feature-[name].js',
  386. filename: '[name].js',
  387. libraryTarget: 'module',
  388. path: path.join(__dirname, 'dist', 'webviews'),
  389. publicPath: '#{root}/dist/webviews/',
  390. },
  391. experiments: {
  392. outputModule: true,
  393. },
  394. optimization: {
  395. minimizer:
  396. mode === 'production'
  397. ? [
  398. env.esbuildMinify
  399. ? new EsbuildPlugin({
  400. css: true,
  401. drop: ['debugger', 'console'],
  402. format: 'esm',
  403. // Keep the class names otherwise @log won't provide a useful name
  404. // keepNames: true,
  405. legalComments: 'none',
  406. minify: true,
  407. target: 'es2022',
  408. treeShaking: true,
  409. })
  410. : new TerserPlugin({
  411. extractComments: false,
  412. parallel: true,
  413. terserOptions: {
  414. compress: {
  415. drop_debugger: true,
  416. drop_console: true,
  417. ecma: 2020,
  418. module: true,
  419. },
  420. ecma: 2020,
  421. format: {
  422. comments: false,
  423. ecma: 2020,
  424. },
  425. // // Keep the class names otherwise @log won't provide a useful name
  426. // keep_classnames: true,
  427. module: true,
  428. },
  429. }),
  430. new ImageMinimizerPlugin({
  431. deleteOriginalAssets: true,
  432. generator: [imageGeneratorConfig],
  433. }),
  434. new CssMinimizerPlugin({
  435. minimizerOptions: {
  436. preset: [
  437. 'cssnano-preset-advanced',
  438. {
  439. discardUnused: false,
  440. mergeIdents: false,
  441. reduceIdents: false,
  442. zindex: false,
  443. },
  444. ],
  445. },
  446. }),
  447. ]
  448. : [],
  449. splitChunks: {
  450. // Disable all non-async code splitting
  451. // chunks: () => false,
  452. cacheGroups: {
  453. default: false,
  454. vendors: false,
  455. },
  456. },
  457. },
  458. module: {
  459. rules: [
  460. {
  461. test: /\.m?js/,
  462. resolve: { fullySpecified: false },
  463. },
  464. {
  465. exclude: /\.d\.ts$/,
  466. include: path.join(__dirname, 'src'),
  467. test: /\.tsx?$/,
  468. use: env.esbuild
  469. ? {
  470. loader: 'esbuild-loader',
  471. options: {
  472. format: 'esm',
  473. implementation: esbuild,
  474. target: 'es2021',
  475. tsconfig: path.join(basePath, 'tsconfig.json'),
  476. },
  477. }
  478. : {
  479. loader: 'ts-loader',
  480. options: {
  481. configFile: path.join(basePath, 'tsconfig.json'),
  482. experimentalWatchApi: true,
  483. transpileOnly: true,
  484. },
  485. },
  486. },
  487. {
  488. test: /\.scss$/,
  489. use: [
  490. {
  491. loader: MiniCssExtractPlugin.loader,
  492. },
  493. {
  494. loader: 'css-loader',
  495. options: {
  496. sourceMap: mode !== 'production',
  497. url: false,
  498. },
  499. },
  500. {
  501. loader: 'sass-loader',
  502. options: {
  503. sourceMap: mode !== 'production',
  504. },
  505. },
  506. ],
  507. exclude: /node_modules/,
  508. },
  509. ],
  510. },
  511. resolve: {
  512. alias: {
  513. '@env': path.resolve(__dirname, 'src', 'env', 'browser'),
  514. '@microsoft/fast-foundation': path.resolve(
  515. __dirname,
  516. 'node_modules/@microsoft/fast-foundation/dist/esm/index.js',
  517. ),
  518. '@microsoft/fast-react-wrapper': path.resolve(
  519. __dirname,
  520. 'node_modules/@microsoft/fast-react-wrapper/dist/esm/index.js',
  521. ),
  522. react: path.resolve(__dirname, 'node_modules', 'react'),
  523. 'react-dom': path.resolve(__dirname, 'node_modules', 'react-dom'),
  524. tslib: path.resolve(__dirname, 'node_modules/tslib/tslib.es6.js'),
  525. },
  526. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  527. modules: [basePath, 'node_modules'],
  528. },
  529. plugins: plugins,
  530. infrastructureLogging:
  531. mode === 'production'
  532. ? undefined
  533. : {
  534. level: 'log', // enables logging required for problem matchers
  535. },
  536. stats: {
  537. preset: 'errors-warnings',
  538. assets: true,
  539. assetsSort: 'name',
  540. assetsSpace: 100,
  541. colors: true,
  542. env: true,
  543. errorsCount: true,
  544. excludeAssets: [/\.(ttf|webp)/],
  545. warningsCount: true,
  546. timings: true,
  547. },
  548. };
  549. }
  550. /**
  551. * @param { 'production' | 'development' | 'none' } mode
  552. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  553. * @returns { CspHtmlPlugin }
  554. */
  555. function getCspHtmlPlugin(mode, env) {
  556. const cspPlugin = new CspHtmlPlugin(
  557. {
  558. 'default-src': "'none'",
  559. 'img-src': ['#{cspSource}', 'https:', 'data:'],
  560. 'script-src':
  561. mode !== 'production'
  562. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-eval'"]
  563. : ['#{cspSource}', "'nonce-#{cspNonce}'"],
  564. 'style-src':
  565. mode === 'production'
  566. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-hashes'"]
  567. : ['#{cspSource}', "'unsafe-hashes'", "'unsafe-inline'"],
  568. 'font-src': ['#{cspSource}'],
  569. },
  570. {
  571. enabled: true,
  572. hashingMethod: 'sha256',
  573. hashEnabled: {
  574. 'script-src': true,
  575. 'style-src': mode === 'production',
  576. },
  577. nonceEnabled: {
  578. 'script-src': true,
  579. 'style-src': mode === 'production',
  580. },
  581. },
  582. );
  583. // Override the nonce creation so we can dynamically generate them at runtime
  584. // @ts-ignore
  585. cspPlugin.createNonce = () => '#{cspNonce}';
  586. return cspPlugin;
  587. }
  588. /**
  589. * @param { 'production' | 'development' | 'none' } mode
  590. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  591. * @returns { ImageMinimizerPlugin.Generator<any> }
  592. */
  593. function getImageMinimizerConfig(mode, env) {
  594. /** @type ImageMinimizerPlugin.Generator<any> */
  595. // @ts-ignore
  596. return env.useSharpForImageOptimization
  597. ? {
  598. type: 'asset',
  599. implementation: ImageMinimizerPlugin.sharpGenerate,
  600. options: {
  601. encodeOptions: {
  602. webp: {
  603. lossless: true,
  604. },
  605. },
  606. },
  607. }
  608. : {
  609. type: 'asset',
  610. implementation: ImageMinimizerPlugin.imageminGenerate,
  611. options: {
  612. plugins: [
  613. [
  614. 'imagemin-webp',
  615. {
  616. lossless: true,
  617. nearLossless: 0,
  618. quality: 100,
  619. method: mode === 'production' ? 4 : 0,
  620. },
  621. ],
  622. ],
  623. },
  624. };
  625. }
  626. /**
  627. * @param { string } name
  628. * @param { boolean } plus
  629. * @param { 'production' | 'development' | 'none' } mode
  630. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; useSharpForImageOptimization?: boolean } | undefined } env
  631. * @returns { HtmlPlugin }
  632. */
  633. function getHtmlPlugin(name, plus, mode, env) {
  634. return new HtmlPlugin({
  635. template: plus ? path.join('plus', name, `${name}.html`) : path.join(name, `${name}.html`),
  636. chunks: [name],
  637. filename: path.join(__dirname, 'dist', 'webviews', `${name}.html`),
  638. inject: true,
  639. scriptLoading: 'module',
  640. inlineSource: mode === 'production' ? '.css$' : undefined,
  641. minify:
  642. mode === 'production'
  643. ? {
  644. removeComments: true,
  645. collapseWhitespace: true,
  646. removeRedundantAttributes: false,
  647. useShortDoctype: true,
  648. removeEmptyAttributes: true,
  649. removeStyleLinkTypeAttributes: true,
  650. keepClosingSlash: true,
  651. minifyCSS: true,
  652. }
  653. : false,
  654. });
  655. }
  656. class InlineChunkHtmlPlugin {
  657. constructor(htmlPlugin, patterns) {
  658. this.htmlPlugin = htmlPlugin;
  659. this.patterns = patterns;
  660. }
  661. getInlinedTag(publicPath, assets, tag) {
  662. if (
  663. (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) &&
  664. (tag.tagName !== 'link' || !(tag.attributes && tag.attributes.href))
  665. ) {
  666. return tag;
  667. }
  668. let chunkName = tag.tagName === 'link' ? tag.attributes.href : tag.attributes.src;
  669. if (publicPath) {
  670. chunkName = chunkName.replace(publicPath, '');
  671. }
  672. if (!this.patterns.some(pattern => chunkName.match(pattern))) {
  673. return tag;
  674. }
  675. const asset = assets[chunkName];
  676. if (asset == null) {
  677. return tag;
  678. }
  679. return { tagName: tag.tagName === 'link' ? 'style' : tag.tagName, innerHTML: asset.source(), closeTag: true };
  680. }
  681. apply(compiler) {
  682. let publicPath = compiler.options.output.publicPath || '';
  683. if (publicPath && !publicPath.endsWith('/')) {
  684. publicPath += '/';
  685. }
  686. compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
  687. const getInlinedTagFn = tag => this.getInlinedTag(publicPath, compilation.assets, tag);
  688. const sortFn = (a, b) => (a.tagName === 'script' ? 1 : -1) - (b.tagName === 'script' ? 1 : -1);
  689. this.htmlPlugin.getHooks(compilation).alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
  690. assets.headTags = assets.headTags.map(getInlinedTagFn).sort(sortFn);
  691. assets.bodyTags = assets.bodyTags.map(getInlinedTagFn).sort(sortFn);
  692. });
  693. });
  694. }
  695. }
  696. const schema = {
  697. type: 'object',
  698. properties: {
  699. config: {
  700. type: 'object',
  701. },
  702. configPath: {
  703. type: 'string',
  704. },
  705. onBefore: {
  706. instanceof: 'Function',
  707. },
  708. onComplete: {
  709. instanceof: 'Function',
  710. },
  711. },
  712. };
  713. class FantasticonPlugin {
  714. alreadyRun = false;
  715. constructor(options = {}) {
  716. this.pluginName = 'fantasticon';
  717. this.options = options;
  718. validate(
  719. // @ts-ignore
  720. schema,
  721. options,
  722. {
  723. name: this.pluginName,
  724. baseDataPath: 'options',
  725. },
  726. );
  727. }
  728. /**
  729. * @param {import("webpack").Compiler} compiler
  730. */
  731. apply(compiler) {
  732. const {
  733. config = undefined,
  734. configPath = undefined,
  735. onBefore = undefined,
  736. onComplete = undefined,
  737. } = this.options;
  738. let loadedConfig;
  739. if (configPath) {
  740. try {
  741. loadedConfig = require(path.join(__dirname, configPath));
  742. } catch (ex) {
  743. console.error(`[${this.pluginName}] Error loading configuration: ${ex}`);
  744. }
  745. }
  746. if (!loadedConfig && !config) {
  747. console.error(`[${this.pluginName}] Error loading configuration: no configuration found`);
  748. return;
  749. }
  750. const fontConfig = { ...(loadedConfig ?? {}), ...(config ?? {}) };
  751. // TODO@eamodio: Figure out how to add watching for the fontConfig.inputDir
  752. // Maybe something like: https://github.com/Fridus/webpack-watch-files-plugin
  753. /**
  754. * @this {FantasticonPlugin}
  755. * @param {import("webpack").Compiler} compiler
  756. */
  757. async function generate(compiler) {
  758. if (compiler.watchMode) {
  759. if (this.alreadyRun) return;
  760. this.alreadyRun = true;
  761. }
  762. const logger = compiler.getInfrastructureLogger(this.pluginName);
  763. logger.log(`Generating icon font...`);
  764. await onBefore?.(fontConfig);
  765. await generateFonts(fontConfig);
  766. await onComplete?.(fontConfig);
  767. logger.log(`Generated icon font`);
  768. }
  769. compiler.hooks.beforeRun.tapPromise(this.pluginName, generate.bind(this));
  770. compiler.hooks.watchRun.tapPromise(this.pluginName, generate.bind(this));
  771. }
  772. }