You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

805 lines
21 KiB

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