Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

804 rindas
21 KiB

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