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
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
  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({ cleanOnceBeforeBuildPatterns: ['**/*', '!**/webviews/**'] }),
  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. cleanOnceBeforeBuildPatterns: ['**/*', path.join(__dirname, 'images/settings/*')],
  202. cleanStaleWebpackAssets: false,
  203. }),
  204. new ForkTsCheckerPlugin({
  205. async: false,
  206. eslint: {
  207. enabled: true,
  208. files: path.join(basePath, '**/*.ts'),
  209. options: { cache: true },
  210. },
  211. formatter: 'basic',
  212. typescript: {
  213. configFile: path.join(basePath, 'tsconfig.json'),
  214. },
  215. }),
  216. new MiniCssExtractPlugin({
  217. filename: '[name].css',
  218. }),
  219. new HtmlPlugin({
  220. template: 'rebase/rebase.html',
  221. chunks: ['rebase'],
  222. filename: path.join(__dirname, 'dist/webviews/rebase.html'),
  223. inject: true,
  224. inlineSource: mode === 'production' ? '.css$' : undefined,
  225. cspPlugin: {
  226. enabled: true,
  227. policy: cspPolicy,
  228. nonceEnabled: {
  229. 'script-src': true,
  230. 'style-src': true,
  231. },
  232. },
  233. minify:
  234. mode === 'production'
  235. ? {
  236. removeComments: true,
  237. collapseWhitespace: true,
  238. removeRedundantAttributes: false,
  239. useShortDoctype: true,
  240. removeEmptyAttributes: true,
  241. removeStyleLinkTypeAttributes: true,
  242. keepClosingSlash: true,
  243. minifyCSS: true,
  244. }
  245. : false,
  246. }),
  247. new HtmlPlugin({
  248. template: 'settings/settings.html',
  249. chunks: ['settings'],
  250. filename: path.join(__dirname, 'dist/webviews/settings.html'),
  251. inject: true,
  252. inlineSource: mode === 'production' ? '.css$' : undefined,
  253. cspPlugin: {
  254. enabled: true,
  255. policy: cspPolicy,
  256. nonceEnabled: {
  257. 'script-src': true,
  258. 'style-src': true,
  259. },
  260. },
  261. minify:
  262. mode === 'production'
  263. ? {
  264. removeComments: true,
  265. collapseWhitespace: true,
  266. removeRedundantAttributes: false,
  267. useShortDoctype: true,
  268. removeEmptyAttributes: true,
  269. removeStyleLinkTypeAttributes: true,
  270. keepClosingSlash: true,
  271. minifyCSS: true,
  272. }
  273. : false,
  274. }),
  275. new HtmlPlugin({
  276. template: 'welcome/welcome.html',
  277. chunks: ['welcome'],
  278. filename: path.join(__dirname, 'dist/webviews/welcome.html'),
  279. inject: true,
  280. inlineSource: mode === 'production' ? '.css$' : undefined,
  281. cspPlugin: {
  282. enabled: true,
  283. policy: cspPolicy,
  284. nonceEnabled: {
  285. 'script-src': true,
  286. 'style-src': true,
  287. },
  288. },
  289. minify:
  290. mode === 'production'
  291. ? {
  292. removeComments: true,
  293. collapseWhitespace: true,
  294. removeRedundantAttributes: false,
  295. useShortDoctype: true,
  296. removeEmptyAttributes: true,
  297. removeStyleLinkTypeAttributes: true,
  298. keepClosingSlash: true,
  299. minifyCSS: true,
  300. }
  301. : false,
  302. }),
  303. new HtmlSkipAssetsPlugin({}),
  304. new CspHtmlPlugin(),
  305. new InlineChunkHtmlPlugin(HtmlPlugin, mode === 'production' ? ['\\.css$'] : []),
  306. new CopyPlugin({
  307. patterns: [
  308. {
  309. from: path.posix.join(basePath.replace(/\\/g, '/'), 'images', 'settings', '*.png'),
  310. to: __dirname.replace(/\\/g, '/'),
  311. },
  312. ],
  313. }),
  314. new ImageMinimizerPlugin({
  315. test: /\.(png)$/i,
  316. filename: '[path][name].webp',
  317. cache: true,
  318. loader: false,
  319. deleteOriginalAssets: true,
  320. minimizerOptions: {
  321. plugins: [
  322. [
  323. 'imagemin-webp',
  324. {
  325. lossless: true,
  326. nearLossless: mode === 'production' ? 0 : 100,
  327. quality: 100,
  328. method: mode === 'production' ? 6 : 0,
  329. },
  330. ],
  331. ],
  332. },
  333. }),
  334. ];
  335. return {
  336. name: 'webviews',
  337. context: basePath,
  338. entry: {
  339. rebase: './rebase/rebase.ts',
  340. settings: './settings/settings.ts',
  341. welcome: './welcome/welcome.ts',
  342. },
  343. mode: mode,
  344. target: 'web',
  345. devtool: 'source-map',
  346. output: {
  347. filename: '[name].js',
  348. path: path.join(__dirname, 'dist/webviews'),
  349. publicPath: '#{root}/dist/webviews/',
  350. },
  351. module: {
  352. rules: [
  353. {
  354. exclude: /\.d\.ts$/,
  355. include: path.join(__dirname, 'src'),
  356. test: /\.tsx?$/,
  357. use: {
  358. loader: 'ts-loader',
  359. options: {
  360. configFile: path.join(basePath, 'tsconfig.json'),
  361. experimentalWatchApi: true,
  362. transpileOnly: true,
  363. },
  364. },
  365. },
  366. {
  367. test: /\.scss$/,
  368. use: [
  369. {
  370. loader: MiniCssExtractPlugin.loader,
  371. },
  372. {
  373. loader: 'css-loader',
  374. options: {
  375. sourceMap: true,
  376. url: false,
  377. },
  378. },
  379. {
  380. loader: 'sass-loader',
  381. options: {
  382. sourceMap: true,
  383. },
  384. },
  385. ],
  386. exclude: /node_modules/,
  387. },
  388. ],
  389. },
  390. resolve: {
  391. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  392. modules: [basePath, 'node_modules'],
  393. symlinks: false,
  394. },
  395. plugins: plugins,
  396. stats: {
  397. preset: 'errors-warnings',
  398. assets: true,
  399. colors: true,
  400. env: true,
  401. errorsCount: true,
  402. warningsCount: true,
  403. timings: true,
  404. },
  405. };
  406. }