Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

605 Zeilen
16 KiB

vor 3 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 5 Jahren
vor 3 Jahren
vor 3 Jahren
vor 3 Jahren
  1. //@ts-check
  2. /** @typedef {import('webpack').Configuration} WebpackConfig **/
  3. /* eslint-disable @typescript-eslint/ban-ts-comment */
  4. /* eslint-disable @typescript-eslint/no-var-requires */
  5. /* eslint-disable @typescript-eslint/strict-boolean-expressions */
  6. /* eslint-disable @typescript-eslint/prefer-optional-chain */
  7. const { spawnSync } = require('child_process');
  8. const path = require('path');
  9. const CircularDependencyPlugin = require('circular-dependency-plugin');
  10. const { CleanWebpackPlugin: CleanPlugin } = require('clean-webpack-plugin');
  11. const CopyPlugin = require('copy-webpack-plugin');
  12. const CspHtmlPlugin = require('csp-html-webpack-plugin');
  13. const esbuild = require('esbuild');
  14. const ForkTsCheckerPlugin = require('fork-ts-checker-webpack-plugin');
  15. const HtmlPlugin = require('html-webpack-plugin');
  16. const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
  17. const JSON5 = require('json5');
  18. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  19. const TerserPlugin = require('terser-webpack-plugin');
  20. const { WebpackError } = require('webpack');
  21. const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  22. module.exports =
  23. /**
  24. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; squoosh?: boolean } | undefined } env
  25. * @param {{ mode: 'production' | 'development' | 'none' | undefined }} argv
  26. * @returns { WebpackConfig[] }
  27. */
  28. function (env, argv) {
  29. const mode = argv.mode || 'none';
  30. env = {
  31. analyzeBundle: false,
  32. analyzeDeps: false,
  33. esbuild: true,
  34. squoosh: true,
  35. ...env,
  36. };
  37. return [
  38. getExtensionConfig('node', mode, env),
  39. getExtensionConfig('webworker', mode, env),
  40. getWebviewsConfig(mode, env),
  41. ];
  42. };
  43. /**
  44. * @param { 'node' | 'webworker' } target
  45. * @param { 'production' | 'development' | 'none' } mode
  46. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; squoosh?: boolean } | undefined } env
  47. * @returns { WebpackConfig }
  48. */
  49. function getExtensionConfig(target, mode, env) {
  50. /**
  51. * @type WebpackConfig['plugins'] | any
  52. */
  53. const plugins = [
  54. new CleanPlugin({ cleanOnceBeforeBuildPatterns: ['!webviews/**'] }),
  55. new ForkTsCheckerPlugin({
  56. async: false,
  57. eslint: {
  58. enabled: true,
  59. files: 'src/**/*.ts',
  60. options: {
  61. // cache: true,
  62. // cacheLocation: path.join(
  63. // __dirname,
  64. // target === 'webworker' ? '.eslintcache.browser' : '.eslintcache',
  65. // ),
  66. overrideConfigFile: path.join(
  67. __dirname,
  68. target === 'webworker' ? '.eslintrc.browser.json' : '.eslintrc.json',
  69. ),
  70. },
  71. },
  72. formatter: 'basic',
  73. typescript: {
  74. configFile: path.join(__dirname, target === 'webworker' ? 'tsconfig.browser.json' : 'tsconfig.json'),
  75. },
  76. }),
  77. ];
  78. if (env.analyzeDeps) {
  79. plugins.push(
  80. new CircularDependencyPlugin({
  81. cwd: __dirname,
  82. exclude: /node_modules/,
  83. failOnError: false,
  84. onDetected: function ({ module: _webpackModuleRecord, paths, compilation }) {
  85. if (paths.some(p => p.includes('container.ts'))) return;
  86. // @ts-ignore
  87. compilation.warnings.push(new WebpackError(paths.join(' -> ')));
  88. },
  89. }),
  90. );
  91. }
  92. if (env.analyzeBundle) {
  93. plugins.push(new BundleAnalyzerPlugin({ analyzerPort: 'auto' }));
  94. }
  95. return {
  96. name: `extension:${target}`,
  97. entry: {
  98. extension: './src/extension.ts',
  99. },
  100. mode: mode,
  101. target: target,
  102. devtool: 'source-map',
  103. output: {
  104. path: target === 'webworker' ? path.join(__dirname, 'dist', 'browser') : path.join(__dirname, 'dist'),
  105. libraryTarget: 'commonjs2',
  106. filename: 'gitlens.js',
  107. chunkFilename: 'feature-[name].js',
  108. },
  109. optimization: {
  110. minimizer: [
  111. new TerserPlugin(
  112. env.esbuild
  113. ? {
  114. minify: TerserPlugin.esbuildMinify,
  115. terserOptions: {
  116. // @ts-ignore
  117. drop: ['debugger'],
  118. format: 'cjs',
  119. minify: true,
  120. treeShaking: true,
  121. // Keep the class names otherwise @log won't provide a useful name
  122. keepNames: true,
  123. target: 'es2020',
  124. },
  125. }
  126. : {
  127. compress: {
  128. drop_debugger: true,
  129. },
  130. extractComments: false,
  131. parallel: true,
  132. terserOptions: {
  133. ecma: 2020,
  134. // Keep the class names otherwise @log won't provide a useful name
  135. keep_classnames: true,
  136. module: true,
  137. },
  138. },
  139. ),
  140. ],
  141. splitChunks:
  142. target === 'webworker'
  143. ? false
  144. : {
  145. // Disable all non-async code splitting
  146. chunks: () => false,
  147. cacheGroups: {
  148. default: false,
  149. vendors: false,
  150. },
  151. },
  152. },
  153. externals: {
  154. vscode: 'commonjs vscode',
  155. },
  156. module: {
  157. rules: [
  158. {
  159. exclude: /\.d\.ts$/,
  160. include: path.join(__dirname, 'src'),
  161. test: /\.tsx?$/,
  162. use: env.esbuild
  163. ? {
  164. loader: 'esbuild-loader',
  165. options: {
  166. implementation: esbuild,
  167. loader: 'ts',
  168. target: ['es2020', 'chrome91', 'node14.16'],
  169. tsconfigRaw: resolveTSConfig(
  170. path.join(
  171. __dirname,
  172. target === 'webworker' ? 'tsconfig.browser.json' : 'tsconfig.json',
  173. ),
  174. ),
  175. },
  176. }
  177. : {
  178. loader: 'ts-loader',
  179. options: {
  180. configFile: path.join(
  181. __dirname,
  182. target === 'webworker' ? 'tsconfig.browser.json' : 'tsconfig.json',
  183. ),
  184. experimentalWatchApi: true,
  185. transpileOnly: true,
  186. },
  187. },
  188. },
  189. ],
  190. },
  191. resolve: {
  192. alias: {
  193. '@env': path.resolve(__dirname, 'src', 'env', target === 'webworker' ? 'browser' : target),
  194. // This dependency is very large, and isn't needed for our use-case
  195. tr46: path.resolve(__dirname, 'patches', 'tr46.js'),
  196. },
  197. fallback: target === 'webworker' ? { path: require.resolve('path-browserify') } : undefined,
  198. mainFields: target === 'webworker' ? ['browser', 'module', 'main'] : ['module', 'main'],
  199. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  200. },
  201. plugins: plugins,
  202. infrastructureLogging: {
  203. level: 'log', // enables logging required for problem matchers
  204. },
  205. stats: {
  206. preset: 'errors-warnings',
  207. assets: true,
  208. colors: true,
  209. env: true,
  210. errorsCount: true,
  211. warningsCount: true,
  212. timings: true,
  213. },
  214. };
  215. }
  216. /**
  217. * @param { 'production' | 'development' | 'none' } mode
  218. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; squoosh?: boolean } | undefined } env
  219. * @returns { WebpackConfig }
  220. */
  221. function getWebviewsConfig(mode, env) {
  222. const basePath = path.join(__dirname, 'src', 'webviews', 'apps');
  223. /** @type WebpackConfig['plugins'] | any */
  224. const plugins = [
  225. new CleanPlugin(
  226. mode === 'production'
  227. ? {
  228. cleanOnceBeforeBuildPatterns: [
  229. path.posix.join(__dirname.replace(/\\/g, '/'), 'images', 'settings', '**'),
  230. ],
  231. dangerouslyAllowCleanPatternsOutsideProject: true,
  232. dry: false,
  233. }
  234. : undefined,
  235. ),
  236. new ForkTsCheckerPlugin({
  237. async: false,
  238. eslint: {
  239. enabled: true,
  240. files: path.join(basePath, '**', '*.ts'),
  241. // options: { cache: true },
  242. },
  243. formatter: 'basic',
  244. typescript: {
  245. configFile: path.join(basePath, 'tsconfig.json'),
  246. },
  247. }),
  248. new MiniCssExtractPlugin({ filename: '[name].css' }),
  249. getHtmlPlugin('home', true, mode, env),
  250. getHtmlPlugin('rebase', false, mode, env),
  251. getHtmlPlugin('settings', false, mode, env),
  252. getHtmlPlugin('welcome', false, mode, env),
  253. getCspHtmlPlugin(mode, env),
  254. new InlineChunkHtmlPlugin(HtmlPlugin, mode === 'production' ? ['\\.css$'] : []),
  255. new CopyPlugin({
  256. patterns: [
  257. {
  258. from: path.posix.join(basePath.replace(/\\/g, '/'), 'images', 'settings', '*.png'),
  259. to: __dirname.replace(/\\/g, '/'),
  260. },
  261. {
  262. from: path.posix.join(
  263. __dirname.replace(/\\/g, '/'),
  264. 'node_modules',
  265. '@vscode',
  266. 'codicons',
  267. 'dist',
  268. 'codicon.ttf',
  269. ),
  270. to: path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews'),
  271. },
  272. {
  273. from: path.posix.join(
  274. __dirname.replace(/\\/g, '/'),
  275. 'node_modules',
  276. '@vscode',
  277. 'webview-ui-toolkit',
  278. 'dist',
  279. 'toolkit.min.js',
  280. ),
  281. to: path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews'),
  282. },
  283. ],
  284. }),
  285. ];
  286. const imageGeneratorConfig = getImageMinimizerConfig(mode, env);
  287. if (mode !== 'production') {
  288. plugins.push(
  289. new ImageMinimizerPlugin({
  290. deleteOriginalAssets: true,
  291. generator: [imageGeneratorConfig],
  292. }),
  293. );
  294. }
  295. return {
  296. name: 'webviews',
  297. context: basePath,
  298. entry: {
  299. home: './premium/home/home.ts',
  300. rebase: './rebase/rebase.ts',
  301. settings: './settings/settings.ts',
  302. welcome: './welcome/welcome.ts',
  303. },
  304. mode: mode,
  305. target: 'web',
  306. devtool: 'source-map',
  307. output: {
  308. filename: '[name].js',
  309. path: path.join(__dirname, 'dist', 'webviews'),
  310. publicPath: '#{root}/dist/webviews/',
  311. },
  312. optimization: {
  313. minimizer: [
  314. new TerserPlugin(
  315. env.esbuild
  316. ? {
  317. minify: TerserPlugin.esbuildMinify,
  318. terserOptions: {
  319. // @ts-ignore
  320. drop: ['debugger', 'console'],
  321. // @ts-ignore
  322. format: 'esm',
  323. minify: true,
  324. treeShaking: true,
  325. // // Keep the class names otherwise @log won't provide a useful name
  326. // keepNames: true,
  327. target: 'es2020',
  328. },
  329. }
  330. : {
  331. compress: {
  332. drop_debugger: true,
  333. drop_console: true,
  334. },
  335. extractComments: false,
  336. parallel: true,
  337. // @ts-ignore
  338. terserOptions: {
  339. ecma: 2020,
  340. // // Keep the class names otherwise @log won't provide a useful name
  341. // keep_classnames: true,
  342. module: true,
  343. },
  344. },
  345. ),
  346. new ImageMinimizerPlugin({
  347. deleteOriginalAssets: true,
  348. generator: [imageGeneratorConfig],
  349. }),
  350. ],
  351. },
  352. module: {
  353. rules: [
  354. {
  355. exclude: /\.d\.ts$/,
  356. include: path.join(__dirname, 'src'),
  357. test: /\.tsx?$/,
  358. use: env.esbuild
  359. ? {
  360. loader: 'esbuild-loader',
  361. options: {
  362. implementation: esbuild,
  363. loader: 'ts',
  364. target: 'es2020',
  365. tsconfigRaw: resolveTSConfig(path.join(basePath, 'tsconfig.json')),
  366. },
  367. }
  368. : {
  369. loader: 'ts-loader',
  370. options: {
  371. configFile: path.join(basePath, 'tsconfig.json'),
  372. experimentalWatchApi: true,
  373. transpileOnly: true,
  374. },
  375. },
  376. },
  377. {
  378. test: /\.scss$/,
  379. use: [
  380. {
  381. loader: MiniCssExtractPlugin.loader,
  382. },
  383. {
  384. loader: 'css-loader',
  385. options: {
  386. sourceMap: true,
  387. url: false,
  388. },
  389. },
  390. {
  391. loader: 'sass-loader',
  392. options: {
  393. sourceMap: true,
  394. },
  395. },
  396. ],
  397. exclude: /node_modules/,
  398. },
  399. ],
  400. },
  401. resolve: {
  402. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  403. modules: [basePath, 'node_modules'],
  404. },
  405. plugins: plugins,
  406. infrastructureLogging: {
  407. level: 'log', // enables logging required for problem matchers
  408. },
  409. stats: {
  410. preset: 'errors-warnings',
  411. assets: true,
  412. colors: true,
  413. env: true,
  414. errorsCount: true,
  415. warningsCount: true,
  416. timings: true,
  417. },
  418. };
  419. }
  420. /**
  421. * @param { 'production' | 'development' | 'none' } mode
  422. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; squoosh?: boolean } | undefined } env
  423. * @returns { CspHtmlPlugin }
  424. */
  425. function getCspHtmlPlugin(mode, env) {
  426. const cspPlugin = new CspHtmlPlugin(
  427. {
  428. 'default-src': "'none'",
  429. 'img-src': ['#{cspSource}', 'https:', 'data:'],
  430. 'script-src':
  431. mode !== 'production'
  432. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-eval'"]
  433. : ['#{cspSource}', "'nonce-#{cspNonce}'"],
  434. 'style-src': ['#{cspSource}', "'nonce-#{cspNonce}'"],
  435. 'font-src': ['#{cspSource}'],
  436. },
  437. {
  438. enabled: true,
  439. hashingMethod: 'sha256',
  440. hashEnabled: {
  441. 'script-src': true,
  442. 'style-src': true,
  443. },
  444. nonceEnabled: {
  445. 'script-src': true,
  446. 'style-src': true,
  447. },
  448. },
  449. );
  450. // Override the nonce creation so we can dynamically generate them at runtime
  451. // @ts-ignore
  452. cspPlugin.createNonce = () => '#{cspNonce}';
  453. return cspPlugin;
  454. }
  455. /**
  456. * @param { 'production' | 'development' | 'none' } mode
  457. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; squoosh?: boolean } | undefined } env
  458. * @returns { ImageMinimizerPlugin.Generator<any> }
  459. */
  460. function getImageMinimizerConfig(mode, env) {
  461. /** @type ImageMinimizerPlugin.Generator<any> */
  462. // @ts-ignore
  463. return env.squoosh
  464. ? {
  465. type: 'asset',
  466. implementation: ImageMinimizerPlugin.squooshGenerate,
  467. options: {
  468. encodeOptions: {
  469. webp: {
  470. // quality: 90,
  471. lossless: 1,
  472. },
  473. },
  474. },
  475. }
  476. : {
  477. type: 'asset',
  478. implementation: ImageMinimizerPlugin.imageminGenerate,
  479. options: {
  480. plugins: [
  481. [
  482. 'imagemin-webp',
  483. {
  484. lossless: true,
  485. nearLossless: 0,
  486. quality: 100,
  487. method: mode === 'production' ? 4 : 0,
  488. },
  489. ],
  490. ],
  491. },
  492. };
  493. }
  494. /**
  495. * @param { string } name
  496. * @param { boolean } premium
  497. * @param { 'production' | 'development' | 'none' } mode
  498. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; squoosh?: boolean } | undefined } env
  499. * @returns { HtmlPlugin }
  500. */
  501. function getHtmlPlugin(name, premium, mode, env) {
  502. return new HtmlPlugin({
  503. template: premium ? path.join('premium', name, `${name}.html`) : path.join(name, `${name}.html`),
  504. chunks: [name],
  505. filename: path.join(__dirname, 'dist', 'webviews', `${name}.html`),
  506. inject: true,
  507. inlineSource: mode === 'production' ? '.css$' : undefined,
  508. minify:
  509. mode === 'production'
  510. ? {
  511. removeComments: true,
  512. collapseWhitespace: true,
  513. removeRedundantAttributes: false,
  514. useShortDoctype: true,
  515. removeEmptyAttributes: true,
  516. removeStyleLinkTypeAttributes: true,
  517. keepClosingSlash: true,
  518. minifyCSS: true,
  519. }
  520. : false,
  521. });
  522. }
  523. class InlineChunkHtmlPlugin {
  524. constructor(htmlPlugin, patterns) {
  525. this.htmlPlugin = htmlPlugin;
  526. this.patterns = patterns;
  527. }
  528. getInlinedTag(publicPath, assets, tag) {
  529. if (
  530. (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) &&
  531. (tag.tagName !== 'link' || !(tag.attributes && tag.attributes.href))
  532. ) {
  533. return tag;
  534. }
  535. let chunkName = tag.tagName === 'link' ? tag.attributes.href : tag.attributes.src;
  536. if (publicPath) {
  537. chunkName = chunkName.replace(publicPath, '');
  538. }
  539. if (!this.patterns.some(pattern => chunkName.match(pattern))) {
  540. return tag;
  541. }
  542. const asset = assets[chunkName];
  543. if (asset == null) {
  544. return tag;
  545. }
  546. return { tagName: tag.tagName === 'link' ? 'style' : tag.tagName, innerHTML: asset.source(), closeTag: true };
  547. }
  548. apply(compiler) {
  549. let publicPath = compiler.options.output.publicPath || '';
  550. if (publicPath && !publicPath.endsWith('/')) {
  551. publicPath += '/';
  552. }
  553. compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
  554. const getInlinedTagFn = tag => this.getInlinedTag(publicPath, compilation.assets, tag);
  555. this.htmlPlugin.getHooks(compilation).alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
  556. assets.headTags = assets.headTags.map(getInlinedTagFn);
  557. assets.bodyTags = assets.bodyTags.map(getInlinedTagFn);
  558. });
  559. });
  560. }
  561. }
  562. /**
  563. * @param { string } configFile
  564. * @returns { string }
  565. */
  566. function resolveTSConfig(configFile) {
  567. const result = spawnSync('yarn', ['tsc', `-p ${configFile}`, '--showConfig'], {
  568. cwd: __dirname,
  569. encoding: 'utf8',
  570. shell: true,
  571. });
  572. const data = result.stdout;
  573. const start = data.indexOf('{');
  574. const end = data.lastIndexOf('}') + 1;
  575. const json = JSON5.parse(data.substring(start, end));
  576. return json;
  577. }