Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

425 строки
11 KiB

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