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.

428 lines
11 KiB

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
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. /* eslint-disable @typescript-eslint/no-var-requires */
  4. /* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
  5. /* eslint-disable @typescript-eslint/strict-boolean-expressions */
  6. /* eslint-disable @typescript-eslint/prefer-optional-chain */
  7. 'use strict';
  8. const fs = require('fs');
  9. const path = require('path');
  10. const glob = require('glob');
  11. const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  12. const { CleanWebpackPlugin: CleanPlugin } = require('clean-webpack-plugin');
  13. const CircularDependencyPlugin = require('circular-dependency-plugin');
  14. const CspHtmlPlugin = require('csp-html-webpack-plugin');
  15. const ForkTsCheckerPlugin = require('fork-ts-checker-webpack-plugin');
  16. const HtmlPlugin = require('html-webpack-plugin');
  17. const HtmlSkipAssetsPlugin = require('html-webpack-skip-assets-plugin').HtmlWebpackSkipAssetsPlugin;
  18. const ImageminPlugin = require('imagemin-webpack-plugin').default;
  19. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  20. const TerserPlugin = require('terser-webpack-plugin');
  21. class InlineChunkHtmlPlugin {
  22. constructor(htmlPlugin, patterns) {
  23. this.htmlPlugin = htmlPlugin;
  24. this.patterns = patterns;
  25. }
  26. getInlinedTag(publicPath, assets, tag) {
  27. if (
  28. (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) &&
  29. (tag.tagName !== 'link' || !(tag.attributes && tag.attributes.href))
  30. ) {
  31. return tag;
  32. }
  33. let chunkName = tag.tagName === 'link' ? tag.attributes.href : tag.attributes.src;
  34. if (publicPath) {
  35. chunkName = chunkName.replace(publicPath, '');
  36. }
  37. if (!this.patterns.some(pattern => chunkName.match(pattern))) {
  38. return tag;
  39. }
  40. const asset = assets[chunkName];
  41. if (asset == null) {
  42. return tag;
  43. }
  44. return { tagName: tag.tagName === 'link' ? 'style' : tag.tagName, innerHTML: asset.source(), closeTag: true };
  45. }
  46. apply(compiler) {
  47. let publicPath = compiler.options.output.publicPath || '';
  48. if (publicPath && !publicPath.endsWith('/')) {
  49. publicPath += '/';
  50. }
  51. compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
  52. const getInlinedTagFn = tag => this.getInlinedTag(publicPath, compilation.assets, tag);
  53. this.htmlPlugin.getHooks(compilation).alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
  54. assets.headTags = assets.headTags.map(getInlinedTagFn);
  55. assets.bodyTags = assets.bodyTags.map(getInlinedTagFn);
  56. });
  57. });
  58. }
  59. }
  60. module.exports =
  61. /**
  62. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; optimizeImages?: boolean; } | undefined } env
  63. * @param {{ mode: 'production' | 'development' | 'none' | undefined; }} argv
  64. * @returns { WebpackConfig[] }
  65. */
  66. function (env, argv) {
  67. const mode = argv.mode || 'none';
  68. env = {
  69. analyzeBundle: false,
  70. analyzeDeps: false,
  71. optimizeImages: mode === 'production',
  72. ...env,
  73. };
  74. if (env.analyzeBundle || env.analyzeDeps) {
  75. env.optimizeImages = false;
  76. } else if (!env.optimizeImages && !fs.existsSync(path.join(__dirname, 'images/settings'))) {
  77. env.optimizeImages = true;
  78. }
  79. return [getExtensionConfig(mode, env), getWebviewsConfig(mode, env)];
  80. };
  81. /**
  82. * @param { 'production' | 'development' | 'none' } mode
  83. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; optimizeImages?: boolean; }} env
  84. * @returns { WebpackConfig }
  85. */
  86. function getExtensionConfig(mode, env) {
  87. /**
  88. * @type WebpackConfig['plugins'] | any
  89. */
  90. const plugins = [
  91. new CleanPlugin({ cleanOnceBeforeBuildPatterns: ['**/*', '!**/webviews/**'] }),
  92. new ForkTsCheckerPlugin({
  93. async: false,
  94. eslint: { enabled: true, files: 'src/**/*.ts', options: { cache: true } },
  95. formatter: 'basic',
  96. }),
  97. ];
  98. if (env.analyzeDeps) {
  99. plugins.push(
  100. new CircularDependencyPlugin({
  101. cwd: __dirname,
  102. exclude: /node_modules/,
  103. failOnError: false,
  104. onDetected: function ({ module: _webpackModuleRecord, paths, compilation }) {
  105. if (paths.some(p => p.includes('container.ts'))) return;
  106. compilation.warnings.push(new Error(paths.join(' -> ')));
  107. },
  108. }),
  109. );
  110. }
  111. if (env.analyzeBundle) {
  112. plugins.push(new BundleAnalyzerPlugin());
  113. }
  114. return {
  115. name: 'extension',
  116. entry: './src/extension.ts',
  117. mode: mode,
  118. target: 'node',
  119. node: {
  120. __dirname: false,
  121. },
  122. devtool: 'source-map',
  123. output: {
  124. path: path.join(__dirname, 'dist'),
  125. libraryTarget: 'commonjs2',
  126. filename: 'gitlens.js',
  127. chunkFilename: 'feature-[name].js',
  128. },
  129. optimization: {
  130. minimizer: [
  131. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  132. // @ts-ignore
  133. new TerserPlugin({
  134. parallel: true,
  135. terserOptions: {
  136. ecma: 2019,
  137. // Keep the class names otherwise @log won't provide a useful name
  138. keep_classnames: true,
  139. module: true,
  140. },
  141. }),
  142. ],
  143. splitChunks: {
  144. cacheGroups: {
  145. defaultVendors: false,
  146. },
  147. },
  148. },
  149. externals: {
  150. vscode: 'commonjs vscode',
  151. },
  152. module: {
  153. rules: [
  154. {
  155. exclude: /\.d\.ts$/,
  156. include: path.join(__dirname, 'src'),
  157. test: /\.tsx?$/,
  158. use: {
  159. loader: 'ts-loader',
  160. options: {
  161. experimentalWatchApi: true,
  162. transpileOnly: true,
  163. },
  164. },
  165. },
  166. ],
  167. },
  168. resolve: {
  169. alias: {
  170. 'universal-user-agent': path.join(__dirname, 'node_modules/universal-user-agent/dist-node/index.js'),
  171. },
  172. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  173. symlinks: false,
  174. },
  175. plugins: plugins,
  176. stats: {
  177. preset: 'errors-warnings',
  178. assets: true,
  179. colors: true,
  180. env: true,
  181. errorsCount: true,
  182. warningsCount: true,
  183. timings: true,
  184. },
  185. };
  186. }
  187. /**
  188. * @param { 'production' | 'development' | 'none' } mode
  189. * @param {{ analyzeBundle?: boolean; analyzeDeps?: boolean; optimizeImages?: boolean; }} env
  190. * @returns { WebpackConfig }
  191. */
  192. function getWebviewsConfig(mode, env) {
  193. const basePath = path.join(__dirname, 'src/webviews/apps');
  194. const clean = ['**/*'];
  195. if (env.optimizeImages) {
  196. console.log('Optimizing images (src/webviews/apps/images/settings/*.png)...');
  197. clean.push(path.join(__dirname, 'images/settings/*'));
  198. }
  199. const cspPolicy = {
  200. 'default-src': "'none'",
  201. 'img-src': ['#{cspSource}', 'https:', 'data:'],
  202. 'script-src': ['#{cspSource}', "'nonce-Z2l0bGVucy1ib290c3RyYXA='"],
  203. 'style-src': ['#{cspSource}'],
  204. };
  205. if (mode !== 'production') {
  206. cspPolicy['script-src'].push("'unsafe-eval'");
  207. }
  208. /**
  209. * @type WebpackConfig['plugins'] | any
  210. */
  211. const plugins = [
  212. new CleanPlugin({ cleanOnceBeforeBuildPatterns: clean, cleanStaleWebpackAssets: false }),
  213. new ForkTsCheckerPlugin({
  214. async: false,
  215. eslint: {
  216. enabled: true,
  217. files: path.join(basePath, '**/*.ts'),
  218. options: { cache: true },
  219. },
  220. formatter: 'basic',
  221. typescript: {
  222. configFile: path.join(basePath, 'tsconfig.json'),
  223. },
  224. }),
  225. new MiniCssExtractPlugin({
  226. filename: '[name].css',
  227. }),
  228. new HtmlPlugin({
  229. template: 'rebase/rebase.html',
  230. chunks: ['rebase'],
  231. filename: path.join(__dirname, 'dist/webviews/rebase.html'),
  232. inject: true,
  233. inlineSource: mode === 'production' ? '.css$' : undefined,
  234. cspPlugin: {
  235. enabled: true,
  236. policy: cspPolicy,
  237. nonceEnabled: {
  238. 'script-src': true,
  239. 'style-src': true,
  240. },
  241. },
  242. minify:
  243. mode === 'production'
  244. ? {
  245. removeComments: true,
  246. collapseWhitespace: true,
  247. removeRedundantAttributes: false,
  248. useShortDoctype: true,
  249. removeEmptyAttributes: true,
  250. removeStyleLinkTypeAttributes: true,
  251. keepClosingSlash: true,
  252. minifyCSS: true,
  253. }
  254. : false,
  255. }),
  256. new HtmlPlugin({
  257. template: 'settings/settings.html',
  258. chunks: ['settings'],
  259. filename: path.join(__dirname, 'dist/webviews/settings.html'),
  260. inject: true,
  261. inlineSource: mode === 'production' ? '.css$' : undefined,
  262. cspPlugin: {
  263. enabled: true,
  264. policy: cspPolicy,
  265. nonceEnabled: {
  266. 'script-src': true,
  267. 'style-src': true,
  268. },
  269. },
  270. minify:
  271. mode === 'production'
  272. ? {
  273. removeComments: true,
  274. collapseWhitespace: true,
  275. removeRedundantAttributes: false,
  276. useShortDoctype: true,
  277. removeEmptyAttributes: true,
  278. removeStyleLinkTypeAttributes: true,
  279. keepClosingSlash: true,
  280. minifyCSS: true,
  281. }
  282. : false,
  283. }),
  284. new HtmlPlugin({
  285. template: 'welcome/welcome.html',
  286. chunks: ['welcome'],
  287. filename: path.join(__dirname, 'dist/webviews/welcome.html'),
  288. inject: true,
  289. inlineSource: mode === 'production' ? '.css$' : undefined,
  290. cspPlugin: {
  291. enabled: true,
  292. policy: cspPolicy,
  293. nonceEnabled: {
  294. 'script-src': true,
  295. 'style-src': true,
  296. },
  297. },
  298. minify:
  299. mode === 'production'
  300. ? {
  301. removeComments: true,
  302. collapseWhitespace: true,
  303. removeRedundantAttributes: false,
  304. useShortDoctype: true,
  305. removeEmptyAttributes: true,
  306. removeStyleLinkTypeAttributes: true,
  307. keepClosingSlash: true,
  308. minifyCSS: true,
  309. }
  310. : false,
  311. }),
  312. new HtmlSkipAssetsPlugin({}),
  313. new CspHtmlPlugin(),
  314. new ImageminPlugin({
  315. disable: !env.optimizeImages,
  316. externalImages: {
  317. context: path.join(basePath, 'images'),
  318. sources: glob.sync(path.join(basePath, 'images/settings/*.png')),
  319. destination: path.join(__dirname, 'images'),
  320. },
  321. cacheFolder: path.join(__dirname, 'node_modules', '.cache', 'imagemin-webpack-plugin'),
  322. gifsicle: null,
  323. jpegtran: null,
  324. optipng: null,
  325. pngquant: {
  326. quality: '85-100',
  327. speed: mode === 'production' ? 1 : 10,
  328. },
  329. svgo: null,
  330. }),
  331. new InlineChunkHtmlPlugin(HtmlPlugin, mode === 'production' ? ['\\.css$'] : []),
  332. ];
  333. return {
  334. name: 'webviews',
  335. context: basePath,
  336. entry: {
  337. rebase: './rebase/rebase.ts',
  338. settings: './settings/settings.ts',
  339. welcome: './welcome/welcome.ts',
  340. },
  341. mode: mode,
  342. target: 'web',
  343. devtool: 'source-map',
  344. output: {
  345. filename: '[name].js',
  346. path: path.join(__dirname, 'dist/webviews'),
  347. publicPath: '#{root}/dist/webviews/',
  348. },
  349. module: {
  350. rules: [
  351. {
  352. exclude: /\.d\.ts$/,
  353. include: path.join(__dirname, 'src'),
  354. test: /\.tsx?$/,
  355. use: {
  356. loader: 'ts-loader',
  357. options: {
  358. configFile: path.join(basePath, 'tsconfig.json'),
  359. experimentalWatchApi: true,
  360. transpileOnly: true,
  361. },
  362. },
  363. },
  364. {
  365. test: /\.scss$/,
  366. use: [
  367. {
  368. loader: MiniCssExtractPlugin.loader,
  369. },
  370. {
  371. loader: 'css-loader',
  372. options: {
  373. sourceMap: true,
  374. url: false,
  375. },
  376. },
  377. {
  378. loader: 'sass-loader',
  379. options: {
  380. sourceMap: true,
  381. },
  382. },
  383. ],
  384. exclude: /node_modules/,
  385. },
  386. ],
  387. },
  388. resolve: {
  389. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  390. modules: [basePath, 'node_modules'],
  391. symlinks: false,
  392. },
  393. plugins: plugins,
  394. stats: {
  395. preset: 'errors-warnings',
  396. assets: true,
  397. colors: true,
  398. env: true,
  399. errorsCount: true,
  400. warningsCount: true,
  401. timings: true,
  402. },
  403. };
  404. }