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.

399 lines
10 KiB

пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 4 година
пре 4 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 4 година
пре 4 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
  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.resolve(__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']
  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. libraryTarget: 'commonjs2',
  125. filename: 'gitlens.js',
  126. chunkFilename: 'feature-[name].js',
  127. },
  128. optimization: {
  129. minimizer: [
  130. new TerserPlugin({
  131. cache: true,
  132. parallel: true,
  133. sourceMap: true,
  134. terserOptions: {
  135. ecma: 8,
  136. // Keep the class names otherwise @log won't provide a useful name
  137. keep_classnames: true,
  138. module: true,
  139. },
  140. }),
  141. ],
  142. splitChunks: {
  143. cacheGroups: {
  144. vendors: false,
  145. },
  146. chunks: 'async',
  147. },
  148. },
  149. externals: {
  150. vscode: 'commonjs vscode',
  151. },
  152. module: {
  153. rules: [
  154. {
  155. exclude: /\.d\.ts$/,
  156. include: path.resolve(__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.resolve(__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. all: false,
  178. assets: true,
  179. builtAt: true,
  180. env: true,
  181. errors: true,
  182. timings: true,
  183. warnings: 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 clean = ['**/*'];
  194. if (env.optimizeImages) {
  195. console.log('Optimizing images (src/webviews/apps/images/settings/*.png)...');
  196. clean.push(path.resolve(__dirname, 'images/settings/*'));
  197. }
  198. const cspPolicy = {
  199. 'default-src': "'none'",
  200. 'img-src': ['#{cspSource}', 'https:', 'data:'],
  201. 'script-src': ['#{cspSource}', "'nonce-Z2l0bGVucy1ib290c3RyYXA='"],
  202. 'style-src': ['#{cspSource}'],
  203. };
  204. if (mode !== 'production') {
  205. cspPolicy['script-src'].push("'unsafe-eval'");
  206. }
  207. /**
  208. * @type WebpackConfig['plugins']
  209. */
  210. const plugins = [
  211. new CleanPlugin({ cleanOnceBeforeBuildPatterns: clean, cleanStaleWebpackAssets: false }),
  212. new ForkTsCheckerPlugin({
  213. async: false,
  214. eslint: {
  215. enabled: true,
  216. files: path.resolve(__dirname, 'src/webviews/apps/**/*.ts'),
  217. options: { cache: true },
  218. },
  219. formatter: 'basic',
  220. typescript: {
  221. configFile: path.resolve(__dirname, 'tsconfig.webviews.json'),
  222. },
  223. }),
  224. new MiniCssExtractPlugin({
  225. filename: '[name].css',
  226. }),
  227. new HtmlPlugin({
  228. template: 'settings/settings.html',
  229. chunks: ['settings', 'settings-styles'],
  230. excludeAssets: [/.+-styles\.js/],
  231. filename: path.resolve(__dirname, 'dist/webviews/settings.html'),
  232. inject: true,
  233. cspPlugin: {
  234. enabled: true,
  235. policy: cspPolicy,
  236. nonceEnabled: {
  237. 'script-src': true,
  238. 'style-src': true,
  239. },
  240. },
  241. minify:
  242. mode === 'production'
  243. ? {
  244. removeComments: true,
  245. collapseWhitespace: true,
  246. removeRedundantAttributes: false,
  247. useShortDoctype: true,
  248. removeEmptyAttributes: true,
  249. removeStyleLinkTypeAttributes: true,
  250. keepClosingSlash: true,
  251. minifyCSS: true,
  252. }
  253. : false,
  254. }),
  255. new HtmlPlugin({
  256. template: 'welcome/welcome.html',
  257. chunks: ['welcome', 'welcome-styles'],
  258. excludeAssets: [/.+-styles\.js/],
  259. filename: path.resolve(__dirname, 'dist/webviews/welcome.html'),
  260. inject: true,
  261. cspPlugin: {
  262. enabled: true,
  263. policy: cspPolicy,
  264. nonceEnabled: {
  265. 'script-src': true,
  266. 'style-src': true,
  267. },
  268. },
  269. minify:
  270. mode === 'production'
  271. ? {
  272. removeComments: true,
  273. collapseWhitespace: true,
  274. removeRedundantAttributes: false,
  275. useShortDoctype: true,
  276. removeEmptyAttributes: true,
  277. removeStyleLinkTypeAttributes: true,
  278. keepClosingSlash: true,
  279. minifyCSS: true,
  280. }
  281. : false,
  282. }),
  283. new HtmlSkipAssetsPlugin({}),
  284. new CspHtmlPlugin(),
  285. new ImageminPlugin({
  286. disable: !env.optimizeImages,
  287. externalImages: {
  288. context: path.resolve(__dirname, 'src/webviews/apps/images'),
  289. sources: glob.sync('src/webviews/apps/images/settings/*.png'),
  290. destination: path.resolve(__dirname, 'images'),
  291. },
  292. cacheFolder: path.resolve(__dirname, 'node_modules', '.cache', 'imagemin-webpack-plugin'),
  293. gifsicle: null,
  294. jpegtran: null,
  295. optipng: null,
  296. pngquant: {
  297. quality: '85-100',
  298. speed: mode === 'production' ? 1 : 10,
  299. },
  300. svgo: null,
  301. }),
  302. new InlineChunkHtmlPlugin(HtmlPlugin, mode === 'production' ? ['\\.css$'] : []),
  303. ];
  304. return {
  305. name: 'webviews',
  306. context: path.resolve(__dirname, 'src/webviews/apps'),
  307. entry: {
  308. settings: ['./settings/settings.ts'],
  309. 'settings-styles': ['./scss/settings.scss'],
  310. welcome: ['./welcome/welcome.ts'],
  311. 'welcome-styles': ['./scss/welcome.scss'],
  312. },
  313. mode: mode,
  314. target: 'web',
  315. devtool: mode === 'production' ? undefined : 'eval-source-map',
  316. output: {
  317. filename: '[name].js',
  318. path: path.resolve(__dirname, 'dist/webviews'),
  319. publicPath: '#{root}/dist/webviews/',
  320. },
  321. module: {
  322. rules: [
  323. {
  324. exclude: /\.d\.ts$/,
  325. include: path.resolve(__dirname, 'src'),
  326. test: /\.tsx?$/,
  327. use: {
  328. loader: 'ts-loader',
  329. options: {
  330. configFile: 'tsconfig.webviews.json',
  331. experimentalWatchApi: true,
  332. transpileOnly: true,
  333. },
  334. },
  335. },
  336. {
  337. test: /\.scss$/,
  338. use: [
  339. {
  340. loader: MiniCssExtractPlugin.loader,
  341. },
  342. {
  343. loader: 'css-loader',
  344. options: {
  345. sourceMap: true,
  346. url: false,
  347. },
  348. },
  349. {
  350. loader: 'sass-loader',
  351. options: {
  352. sourceMap: true,
  353. },
  354. },
  355. ],
  356. exclude: /node_modules/,
  357. },
  358. ],
  359. },
  360. resolve: {
  361. extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  362. modules: [path.resolve(__dirname, 'src/webviews/apps'), 'node_modules'],
  363. symlinks: false,
  364. },
  365. plugins: plugins,
  366. stats: {
  367. all: false,
  368. assets: true,
  369. builtAt: true,
  370. env: true,
  371. errors: true,
  372. timings: true,
  373. warnings: true,
  374. },
  375. };
  376. }