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.

webpack.config.js 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2020 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. /* eslint-disable import/no-extraneous-dependencies, complexity */
  21. const path = require('path');
  22. const CleanWebpackPlugin = require('clean-webpack-plugin');
  23. const CopyWebpackPlugin = require('copy-webpack-plugin');
  24. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  25. const HtmlWebpackPlugin = require('html-webpack-plugin');
  26. const LodashPlugin = require('lodash-webpack-plugin');
  27. const webpack = require('webpack');
  28. const InterpolateHtmlPlugin = require('./InterpolateHtmlPlugin');
  29. const paths = require('./paths');
  30. const utils = require('./utils');
  31. /*
  32. This webpack config is actually two: one for modern browsers and one for the legacy ones (e.g. ie11)
  33. The modern one transpilies the code to ES2018 (i.e. with classes, async functions, etc.) and
  34. does not include any polyfills. It's included in the result index.html using <script type="module">.
  35. Legacy browsers ignore this tag.
  36. The legacy one transpilies the code to ES5 and polyfills ES5+ features (promises, generators, etc.).
  37. It's included in the result index.html using <script nomodule>. Modern browsers do not load such scripts.
  38. There is a trick to have both scripts in the index.html. We generate this file only once, during the
  39. build for modern browsers. We want unique file names for each version to invalidate browser cache.
  40. For modern browsers we generate a file suffix using the content hash (as previously). For legacy ones
  41. we can't do the same, because we need to know the file names without the build.
  42. To work-around the problem, we use a build timestamp which is added to the legacy build file names.
  43. This way assuming that the build generates exactly the same entry chunks, we know the name of the
  44. legacy files. Inside index.html template we use a simple regex to replace the file hash of a modern
  45. file name to the timestamp. To simplify the regex we use ".m." suffix for modern files.
  46. This whole thing might be simplified when (if) the following issue is resolved:
  47. https://github.com/jantimon/html-webpack-plugin/issues/1051
  48. */
  49. module.exports = ({ production = true, release = false }) => {
  50. const timestamp = Date.now();
  51. const commonConfig = {
  52. mode: production ? 'production' : 'development',
  53. devtool: production && release ? 'source-map' : 'cheap-module-source-map',
  54. resolve: {
  55. // Add '.ts' and '.tsx' as resolvable extensions.
  56. extensions: ['.ts', '.tsx', '.js', '.json'],
  57. // import from 'Docs/foo.md' is rewritten to import from 'sonar-docs/src/foo.md'
  58. alias: {
  59. Docs: path.resolve(__dirname, '../../sonar-docs/src'),
  60. // This avoid having multi instance of @emotion when developing with yarn link on sonar-ui-common
  61. '@emotion': path.resolve(__dirname, '../node_modules/@emotion'),
  62. // This avoid having multi instance of react when developing with yarn link on sonar-ui-common
  63. // See https://reactjs.org/warnings/invalid-hook-call-warning.html
  64. react: path.resolve(__dirname, '../node_modules/react'),
  65. 'react-dom': path.resolve(__dirname, '../node_modules/react-dom')
  66. }
  67. },
  68. optimization: {
  69. splitChunks: {
  70. chunks: 'all',
  71. automaticNameDelimiter: '-',
  72. maxSize: 310000
  73. },
  74. minimize: production && release
  75. }
  76. };
  77. const commonRules = [
  78. {
  79. // extract styles from 'app/' into separate file
  80. test: /\.css$/,
  81. include: path.resolve(__dirname, '../src/main/js/app/styles'),
  82. use: [
  83. production ? MiniCssExtractPlugin.loader : 'style-loader',
  84. utils.cssLoader(),
  85. utils.postcssLoader(production)
  86. ]
  87. },
  88. {
  89. // inline all other styles
  90. test: /\.css$/,
  91. exclude: path.resolve(__dirname, '../src/main/js/app/styles'),
  92. use: ['style-loader', utils.cssLoader(), utils.postcssLoader(production)]
  93. },
  94. {
  95. test: /\.md$/,
  96. use: 'raw-loader'
  97. },
  98. { test: require.resolve('react'), loader: 'expose-loader?React' },
  99. { test: require.resolve('react-dom'), loader: 'expose-loader?ReactDOM' },
  100. {
  101. test: /\.directory-loader\.js$/,
  102. loader: path.resolve(__dirname, 'documentation-loader/index.js')
  103. }
  104. ];
  105. const commonPlugins = [
  106. production &&
  107. new MiniCssExtractPlugin({
  108. filename: 'css/[name].[chunkhash:8].css',
  109. chunkFilename: 'css/[name].[chunkhash:8].chunk.css'
  110. }),
  111. new LodashPlugin({
  112. // keep these features
  113. // https://github.com/lodash/lodash-webpack-plugin#feature-sets
  114. shorthands: true,
  115. collections: true,
  116. exotics: true, // used to compare "exotic" values, like dates
  117. memoizing: true,
  118. flattening: true
  119. })
  120. ];
  121. return [
  122. Object.assign({ name: 'modern' }, commonConfig, {
  123. entry: [
  124. !production && require.resolve('react-dev-utils/webpackHotDevClient'),
  125. !production && require.resolve('react-error-overlay'),
  126. './src/main/js/app/utils/setPublicPath.js',
  127. './src/main/js/app/index.ts'
  128. ].filter(Boolean),
  129. output: {
  130. path: paths.appBuild,
  131. pathinfo: !production,
  132. filename: production ? 'js/[name].m.[chunkhash:8].js' : 'js/[name].js',
  133. chunkFilename: production ? 'js/[name].m.[chunkhash:8].chunk.js' : 'js/[name].chunk.js'
  134. },
  135. module: {
  136. rules: [
  137. {
  138. test: /(\.js$|\.ts(x?)$)/,
  139. exclude: /(node_modules|libs)/,
  140. use: [
  141. { loader: 'babel-loader' },
  142. {
  143. loader: 'ts-loader',
  144. options: { transpileOnly: true }
  145. }
  146. ]
  147. },
  148. ...commonRules
  149. ]
  150. },
  151. plugins: [
  152. production && new CleanWebpackPlugin(),
  153. production &&
  154. new CopyWebpackPlugin([
  155. {
  156. from: paths.docImages,
  157. to: paths.appBuild + '/images/embed-doc/images'
  158. }
  159. ]),
  160. production &&
  161. new CopyWebpackPlugin([
  162. {
  163. from: paths.appPublic,
  164. to: paths.appBuild,
  165. ignore: [paths.appHtml]
  166. }
  167. ]),
  168. ...commonPlugins,
  169. new HtmlWebpackPlugin({
  170. inject: false,
  171. template: paths.appHtml,
  172. minify: utils.minifyParams({ production: production && release }),
  173. timestamp
  174. }),
  175. // keep `InterpolateHtmlPlugin` after `HtmlWebpackPlugin`
  176. !production &&
  177. new InterpolateHtmlPlugin({
  178. WEB_CONTEXT: process.env.WEB_CONTEXT || '',
  179. SERVER_STATUS: process.env.SERVER_STATUS || 'UP',
  180. INSTANCE: process.env.INSTANCE || 'SonarQube',
  181. OFFICIAL: process.env.OFFICIAL || 'true'
  182. }),
  183. !production && new webpack.HotModuleReplacementPlugin()
  184. ].filter(Boolean),
  185. performance:
  186. production && release
  187. ? {
  188. // ignore source maps and documentation chunk
  189. assetFilter: assetFilename =>
  190. !assetFilename.endsWith('.map') && !assetFilename.startsWith('js/docs'),
  191. maxAssetSize: 310000,
  192. hints: 'error'
  193. }
  194. : undefined
  195. }),
  196. Object.assign({ name: 'legacy' }, commonConfig, {
  197. entry: [
  198. !production && require.resolve('react-dev-utils/webpackHotDevClient'),
  199. require.resolve('./polyfills'),
  200. !production && require.resolve('react-error-overlay'),
  201. './src/main/js/app/utils/setPublicPath.js',
  202. './src/main/js/app/index.ts'
  203. ].filter(Boolean),
  204. output: {
  205. path: paths.appBuild,
  206. pathinfo: !production,
  207. filename: production ? `js/[name].${timestamp}.js` : 'js/[name].js',
  208. chunkFilename: production ? `js/[name].${timestamp}.chunk.js` : 'js/[name].chunk.js'
  209. },
  210. module: {
  211. rules: [
  212. {
  213. test: /(\.js$|\.ts(x?)$)/,
  214. exclude: /(node_modules|libs)/,
  215. use: [
  216. {
  217. loader: 'babel-loader',
  218. options: {
  219. configFile: path.join(__dirname, '../babel.config.legacy.js')
  220. }
  221. },
  222. {
  223. loader: 'ts-loader',
  224. options: {
  225. configFile: 'tsconfig.legacy.json',
  226. transpileOnly: true
  227. }
  228. }
  229. ]
  230. },
  231. ...commonRules
  232. ]
  233. },
  234. plugins: [...commonPlugins, !production && new webpack.HotModuleReplacementPlugin()].filter(
  235. Boolean
  236. )
  237. })
  238. ];
  239. };