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.

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