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.

564 lines
14 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
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
3 years ago
3 years ago
3 years ago
  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());
  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. env.esbuild
  112. ? new TerserPlugin({
  113. minify: TerserPlugin.esbuildMinify,
  114. terserOptions: {
  115. drop: ['debugger'],
  116. // @ts-ignore
  117. format: 'cjs',
  118. minify: true,
  119. treeShaking: true,
  120. // Keep the class names otherwise @log won't provide a useful name
  121. keepNames: true,
  122. target: 'es2020',
  123. },
  124. })
  125. : new TerserPlugin({
  126. drop_debugger: true,
  127. extractComments: false,
  128. parallel: true,
  129. // @ts-ignore
  130. terserOptions: {
  131. ecma: 2020,
  132. // Keep the class names otherwise @log won't provide a useful name
  133. keep_classnames: true,
  134. module: true,
  135. },
  136. }),
  137. ],
  138. splitChunks:
  139. target === 'webworker'
  140. ? false
  141. : {
  142. // Disable all non-async code splitting
  143. chunks: () => false,
  144. cacheGroups: {
  145. default: false,
  146. vendors: false,
  147. },
  148. },
  149. },
  150. externals: {
  151. vscode: 'commonjs vscode',
  152. },
  153. module: {
  154. rules: [
  155. {
  156. exclude: /\.d\.ts$/,
  157. include: path.join(__dirname, 'src'),
  158. test: /\.tsx?$/,
  159. use: env.esbuild
  160. ? {
  161. loader: 'esbuild-loader',
  162. options: {
  163. implementation: esbuild,
  164. loader: 'ts',
  165. target: ['es2020', 'chrome91', 'node14.16'],
  166. tsconfigRaw: resolveTSConfig(
  167. path.join(
  168. __dirname,
  169. target === 'webworker' ? 'tsconfig.browser.json' : 'tsconfig.json',
  170. ),
  171. ),
  172. },
  173. }
  174. : {
  175. loader: 'ts-loader',
  176. options: {
  177. configFile: path.join(
  178. __dirname,
  179. target === 'webworker' ? 'tsconfig.browser.json' : 'tsconfig.json',
  180. ),
  181. experimentalWatchApi: true,
  182. transpileOnly: true,
  183. },
  184. },
  185. },
  186. ],
  187. },
  188. resolve: {
  189. alias: { '@env': path.resolve(__dirname, 'src', 'env', target === 'webworker' ? 'browser' : target) },
  190. fallback: target === 'webworker' ? { path: require.resolve('path-browserify') } : undefined,
  191. mainFields: target === 'webworker' ? ['browser', 'module', 'main'] : ['module', 'main'],
  192. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  193. },
  194. plugins: plugins,
  195. infrastructureLogging: {
  196. level: 'log', // enables logging required for problem matchers
  197. },
  198. stats: {
  199. preset: 'errors-warnings',
  200. assets: true,
  201. colors: true,
  202. env: true,
  203. errorsCount: true,
  204. warningsCount: true,
  205. timings: true,
  206. },
  207. };
  208. }
  209. /**
  210. * @param { 'production' | 'development' | 'none' } mode
  211. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; esbuild?: boolean; squoosh?: boolean } | undefined } env
  212. * @returns { WebpackConfig }
  213. */
  214. function getWebviewsConfig(mode, env) {
  215. const basePath = path.join(__dirname, 'src', 'webviews', 'apps');
  216. const cspHtmlPlugin = new CspHtmlPlugin(
  217. {
  218. 'default-src': "'none'",
  219. 'img-src': ['#{cspSource}', 'https:', 'data:'],
  220. 'script-src':
  221. mode !== 'production'
  222. ? ['#{cspSource}', "'nonce-#{cspNonce}'", "'unsafe-eval'"]
  223. : ['#{cspSource}', "'nonce-#{cspNonce}'"],
  224. 'style-src': ['#{cspSource}', "'nonce-#{cspNonce}'"],
  225. 'font-src': ['#{cspSource}'],
  226. },
  227. {
  228. enabled: true,
  229. hashingMethod: 'sha256',
  230. hashEnabled: {
  231. 'script-src': true,
  232. 'style-src': true,
  233. },
  234. nonceEnabled: {
  235. 'script-src': true,
  236. 'style-src': true,
  237. },
  238. },
  239. );
  240. // Override the nonce creation so we can dynamically generate them at runtime
  241. // @ts-ignore
  242. cspHtmlPlugin.createNonce = () => '#{cspNonce}';
  243. /** @type ImageMinimizerPlugin.Generator<any> */
  244. // @ts-ignore
  245. let imageGeneratorConfig = env.squoosh
  246. ? {
  247. type: 'asset',
  248. implementation: ImageMinimizerPlugin.squooshGenerate,
  249. options: {
  250. encodeOptions: {
  251. webp: {
  252. // quality: 90,
  253. lossless: 1,
  254. },
  255. },
  256. },
  257. }
  258. : {
  259. type: 'asset',
  260. implementation: ImageMinimizerPlugin.imageminGenerate,
  261. options: {
  262. plugins: [
  263. [
  264. 'imagemin-webp',
  265. {
  266. lossless: true,
  267. nearLossless: 0,
  268. quality: 100,
  269. method: mode === 'production' ? 4 : 0,
  270. },
  271. ],
  272. ],
  273. },
  274. };
  275. /** @type WebpackConfig['plugins'] | any */
  276. const plugins = [
  277. new CleanPlugin(
  278. mode === 'production'
  279. ? {
  280. cleanOnceBeforeBuildPatterns: [
  281. path.posix.join(__dirname.replace(/\\/g, '/'), 'images', 'settings', '**'),
  282. ],
  283. dangerouslyAllowCleanPatternsOutsideProject: true,
  284. dry: false,
  285. }
  286. : undefined,
  287. ),
  288. new ForkTsCheckerPlugin({
  289. async: false,
  290. eslint: {
  291. enabled: true,
  292. files: path.join(basePath, '**', '*.ts'),
  293. // options: { cache: true },
  294. },
  295. formatter: 'basic',
  296. typescript: {
  297. configFile: path.join(basePath, 'tsconfig.json'),
  298. },
  299. }),
  300. new MiniCssExtractPlugin({
  301. filename: '[name].css',
  302. }),
  303. new HtmlPlugin({
  304. template: 'rebase/rebase.html',
  305. chunks: ['rebase'],
  306. filename: path.join(__dirname, 'dist', 'webviews', 'rebase.html'),
  307. inject: true,
  308. inlineSource: mode === 'production' ? '.css$' : undefined,
  309. minify:
  310. mode === 'production'
  311. ? {
  312. removeComments: true,
  313. collapseWhitespace: true,
  314. removeRedundantAttributes: false,
  315. useShortDoctype: true,
  316. removeEmptyAttributes: true,
  317. removeStyleLinkTypeAttributes: true,
  318. keepClosingSlash: true,
  319. minifyCSS: true,
  320. }
  321. : false,
  322. }),
  323. new HtmlPlugin({
  324. template: 'settings/settings.html',
  325. chunks: ['settings'],
  326. filename: path.join(__dirname, 'dist', 'webviews', 'settings.html'),
  327. inject: true,
  328. inlineSource: mode === 'production' ? '.css$' : undefined,
  329. minify:
  330. mode === 'production'
  331. ? {
  332. removeComments: true,
  333. collapseWhitespace: true,
  334. removeRedundantAttributes: false,
  335. useShortDoctype: true,
  336. removeEmptyAttributes: true,
  337. removeStyleLinkTypeAttributes: true,
  338. keepClosingSlash: true,
  339. minifyCSS: true,
  340. }
  341. : false,
  342. }),
  343. new HtmlPlugin({
  344. template: 'welcome/welcome.html',
  345. chunks: ['welcome'],
  346. filename: path.join(__dirname, 'dist', 'webviews', 'welcome.html'),
  347. inject: true,
  348. inlineSource: mode === 'production' ? '.css$' : undefined,
  349. minify:
  350. mode === 'production'
  351. ? {
  352. removeComments: true,
  353. collapseWhitespace: true,
  354. removeRedundantAttributes: false,
  355. useShortDoctype: true,
  356. removeEmptyAttributes: true,
  357. removeStyleLinkTypeAttributes: true,
  358. keepClosingSlash: true,
  359. minifyCSS: true,
  360. }
  361. : false,
  362. }),
  363. cspHtmlPlugin,
  364. new InlineChunkHtmlPlugin(HtmlPlugin, mode === 'production' ? ['\\.css$'] : []),
  365. new CopyPlugin({
  366. patterns: [
  367. {
  368. from: path.posix.join(basePath.replace(/\\/g, '/'), 'images', 'settings', '*.png'),
  369. to: __dirname.replace(/\\/g, '/'),
  370. },
  371. {
  372. from: path.posix.join(
  373. __dirname.replace(/\\/g, '/'),
  374. 'node_modules',
  375. '@vscode',
  376. 'codicons',
  377. 'dist',
  378. 'codicon.ttf',
  379. ),
  380. to: path.posix.join(__dirname.replace(/\\/g, '/'), 'dist', 'webviews'),
  381. },
  382. ],
  383. }),
  384. ];
  385. if (mode !== 'production') {
  386. plugins.push(
  387. new ImageMinimizerPlugin({
  388. deleteOriginalAssets: true,
  389. generator: [imageGeneratorConfig],
  390. }),
  391. );
  392. }
  393. return {
  394. name: 'webviews',
  395. context: basePath,
  396. entry: {
  397. rebase: './rebase/rebase.ts',
  398. settings: './settings/settings.ts',
  399. welcome: './welcome/welcome.ts',
  400. },
  401. mode: mode,
  402. target: 'web',
  403. devtool: 'source-map',
  404. output: {
  405. filename: '[name].js',
  406. path: path.join(__dirname, 'dist', 'webviews'),
  407. publicPath: '#{root}/dist/webviews/',
  408. },
  409. optimization: {
  410. minimizer: [
  411. new ImageMinimizerPlugin({
  412. deleteOriginalAssets: true,
  413. generator: [imageGeneratorConfig],
  414. }),
  415. ],
  416. },
  417. module: {
  418. rules: [
  419. {
  420. exclude: /\.d\.ts$/,
  421. include: path.join(__dirname, 'src'),
  422. test: /\.tsx?$/,
  423. use: env.esbuild
  424. ? {
  425. loader: 'esbuild-loader',
  426. options: {
  427. implementation: esbuild,
  428. loader: 'ts',
  429. target: 'es2020',
  430. tsconfigRaw: resolveTSConfig(path.join(basePath, 'tsconfig.json')),
  431. },
  432. }
  433. : {
  434. loader: 'ts-loader',
  435. options: {
  436. configFile: path.join(basePath, 'tsconfig.json'),
  437. experimentalWatchApi: true,
  438. transpileOnly: true,
  439. },
  440. },
  441. },
  442. {
  443. test: /\.scss$/,
  444. use: [
  445. {
  446. loader: MiniCssExtractPlugin.loader,
  447. },
  448. {
  449. loader: 'css-loader',
  450. options: {
  451. sourceMap: true,
  452. url: false,
  453. },
  454. },
  455. {
  456. loader: 'sass-loader',
  457. options: {
  458. sourceMap: true,
  459. },
  460. },
  461. ],
  462. exclude: /node_modules/,
  463. },
  464. ],
  465. },
  466. resolve: {
  467. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  468. modules: [basePath, 'node_modules'],
  469. },
  470. plugins: plugins,
  471. infrastructureLogging: {
  472. level: 'log', // enables logging required for problem matchers
  473. },
  474. stats: {
  475. preset: 'errors-warnings',
  476. assets: true,
  477. colors: true,
  478. env: true,
  479. errorsCount: true,
  480. warningsCount: true,
  481. timings: true,
  482. },
  483. };
  484. }
  485. class InlineChunkHtmlPlugin {
  486. constructor(htmlPlugin, patterns) {
  487. this.htmlPlugin = htmlPlugin;
  488. this.patterns = patterns;
  489. }
  490. getInlinedTag(publicPath, assets, tag) {
  491. if (
  492. (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) &&
  493. (tag.tagName !== 'link' || !(tag.attributes && tag.attributes.href))
  494. ) {
  495. return tag;
  496. }
  497. let chunkName = tag.tagName === 'link' ? tag.attributes.href : tag.attributes.src;
  498. if (publicPath) {
  499. chunkName = chunkName.replace(publicPath, '');
  500. }
  501. if (!this.patterns.some(pattern => chunkName.match(pattern))) {
  502. return tag;
  503. }
  504. const asset = assets[chunkName];
  505. if (asset == null) {
  506. return tag;
  507. }
  508. return { tagName: tag.tagName === 'link' ? 'style' : tag.tagName, innerHTML: asset.source(), closeTag: true };
  509. }
  510. apply(compiler) {
  511. let publicPath = compiler.options.output.publicPath || '';
  512. if (publicPath && !publicPath.endsWith('/')) {
  513. publicPath += '/';
  514. }
  515. compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
  516. const getInlinedTagFn = tag => this.getInlinedTag(publicPath, compilation.assets, tag);
  517. this.htmlPlugin.getHooks(compilation).alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
  518. assets.headTags = assets.headTags.map(getInlinedTagFn);
  519. assets.bodyTags = assets.bodyTags.map(getInlinedTagFn);
  520. });
  521. });
  522. }
  523. }
  524. /**
  525. * @param { string } configFile
  526. * @returns { string }
  527. */
  528. function resolveTSConfig(configFile) {
  529. const result = spawnSync('yarn', ['tsc', `-p ${configFile}`, '--showConfig'], {
  530. cwd: __dirname,
  531. encoding: 'utf8',
  532. shell: true,
  533. });
  534. const data = result.stdout;
  535. const start = data.indexOf('{');
  536. const end = data.lastIndexOf('}') + 1;
  537. const json = JSON5.parse(data.substring(start, end));
  538. return json;
  539. }