Nessuna descrizione

webpack.config.prod.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. 'use strict';
  2. const autoprefixer = require('autoprefixer');
  3. const path = require('path');
  4. const webpack = require('webpack');
  5. const HtmlWebpackPlugin = require('html-webpack-plugin');
  6. const ExtractTextPlugin = require('extract-text-webpack-plugin');
  7. const ManifestPlugin = require('webpack-manifest-plugin');
  8. const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
  9. const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
  10. const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
  11. const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
  12. const paths = require('./paths');
  13. const getClientEnvironment = require('./env');
  14. const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
  15. const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
  16. // Webpack uses `publicPath` to determine where the app is being served from.
  17. // It requires a trailing slash, or the file assets will get an incorrect path.
  18. const publicPath = paths.servedPath;
  19. // Some apps do not use client-side routing with pushState.
  20. // For these, "homepage" can be set to "." to enable relative asset paths.
  21. const shouldUseRelativeAssetPaths = publicPath === './';
  22. // Source maps are resource heavy and can cause out of memory issue for large source files.
  23. const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
  24. // `publicUrl` is just like `publicPath`, but we will provide it to our app
  25. // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
  26. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
  27. const publicUrl = publicPath.slice(0, -1);
  28. // Get environment variables to inject into our app.
  29. const env = getClientEnvironment(publicUrl);
  30. // Assert this just to be safe.
  31. // Development builds of React are slow and not intended for production.
  32. if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  33. throw new Error('Production builds must have NODE_ENV=production.');
  34. }
  35. // Note: defined here because it will be used more than once.
  36. const cssFilename = 'static/css/[name].[contenthash:8].css';
  37. // ExtractTextPlugin expects the build output to be flat.
  38. // (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
  39. // However, our output is structured with css, js and media folders.
  40. // To have this structure working with relative paths, we have to use custom options.
  41. const extractTextPluginOptions = shouldUseRelativeAssetPaths
  42. ? // Making sure that the publicPath goes back to to build folder.
  43. { publicPath: Array(cssFilename.split('/').length).join('../') }
  44. : {};
  45. // This is the production configuration.
  46. // It compiles slowly and is focused on producing a fast and minimal bundle.
  47. // The development configuration is different and lives in a separate file.
  48. module.exports = {
  49. // Don't attempt to continue if there are any errors.
  50. bail: true,
  51. // We generate sourcemaps in production. This is slow but gives good results.
  52. // You can exclude the *.map files from the build during deployment.
  53. devtool: shouldUseSourceMap ? 'source-map' : false,
  54. // In production, we only want to load the polyfills and the app code.
  55. entry: [require.resolve('./polyfills'), paths.appIndexJs],
  56. output: {
  57. // The build folder.
  58. path: paths.appBuild,
  59. // Generated JS file names (with nested folders).
  60. // There will be one main bundle, and one file per asynchronous chunk.
  61. // We don't currently advertise code splitting but Webpack supports it.
  62. filename: 'static/js/[name].[chunkhash:8].js',
  63. chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
  64. // We inferred the "public path" (such as / or /my-project) from homepage.
  65. publicPath: publicPath,
  66. // Point sourcemap entries to original disk location (format as URL on Windows)
  67. devtoolModuleFilenameTemplate: info =>
  68. path
  69. .relative(paths.appSrc, info.absoluteResourcePath)
  70. .replace(/\\/g, '/'),
  71. },
  72. resolve: {
  73. // This allows you to set a fallback for where Webpack should look for modules.
  74. // We placed these paths second because we want `node_modules` to "win"
  75. // if there are any conflicts. This matches Node resolution mechanism.
  76. // https://github.com/facebookincubator/create-react-app/issues/253
  77. modules: ['node_modules', paths.appNodeModules].concat(
  78. // It is guaranteed to exist because we tweak it in `env.js`
  79. process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
  80. ),
  81. // These are the reasonable defaults supported by the Node ecosystem.
  82. // We also include JSX as a common component filename extension to support
  83. // some tools, although we do not recommend using it, see:
  84. // https://github.com/facebookincubator/create-react-app/issues/290
  85. // `web` extension prefixes have been added for better support
  86. // for React Native Web.
  87. extensions: [
  88. '.mjs',
  89. '.web.ts',
  90. '.ts',
  91. '.web.tsx',
  92. '.tsx',
  93. '.web.js',
  94. '.js',
  95. '.json',
  96. '.web.jsx',
  97. '.jsx',
  98. ],
  99. alias: {
  100. // Support React Native Web
  101. // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  102. 'react-native': 'react-native-web',
  103. },
  104. plugins: [
  105. // Prevents users from importing files from outside of src/ (or node_modules/).
  106. // This often causes confusion because we only process files within src/ with babel.
  107. // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
  108. // please link the files into your node_modules/ and let module-resolution kick in.
  109. // Make sure your source files are compiled, as they will not be processed in any way.
  110. new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
  111. new TsconfigPathsPlugin({ configFile: paths.appTsConfig }),
  112. ],
  113. },
  114. module: {
  115. strictExportPresence: true,
  116. rules: [
  117. // TODO: Disable require.ensure as it's not a standard language feature.
  118. // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
  119. // { parser: { requireEnsure: false } },
  120. {
  121. test: /\.(js|jsx|mjs)$/,
  122. loader: require.resolve('source-map-loader'),
  123. enforce: 'pre',
  124. include: paths.appSrc,
  125. },
  126. {
  127. // "oneOf" will traverse all following loaders until one will
  128. // match the requirements. When no loader matches it will fall
  129. // back to the "file" loader at the end of the loader list.
  130. oneOf: [
  131. // "url" loader works just like "file" loader but it also embeds
  132. // assets smaller than specified size as data URLs to avoid requests.
  133. {
  134. test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
  135. loader: require.resolve('url-loader'),
  136. options: {
  137. limit: 10000,
  138. name: 'static/media/[name].[hash:8].[ext]',
  139. },
  140. },
  141. {
  142. test: /\.(js|jsx|mjs)$/,
  143. include: paths.appSrc,
  144. loader: require.resolve('babel-loader'),
  145. options: {
  146. compact: true,
  147. },
  148. },
  149. // Compile .tsx?
  150. {
  151. test: /\.(ts|tsx)$/,
  152. include: paths.appSrc,
  153. use: [
  154. {
  155. loader: require.resolve('ts-loader'),
  156. options: {
  157. // disable type checker - we will use it in fork plugin
  158. transpileOnly: true,
  159. configFile: paths.appTsProdConfig
  160. },
  161. },
  162. ],
  163. },
  164. // The notation here is somewhat confusing.
  165. // "postcss" loader applies autoprefixer to our CSS.
  166. // "css" loader resolves paths in CSS and adds assets as dependencies.
  167. // "style" loader normally turns CSS into JS modules injecting <style>,
  168. // but unlike in development configuration, we do something different.
  169. // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
  170. // (second argument), then grabs the result CSS and puts it into a
  171. // separate file in our build process. This way we actually ship
  172. // a single CSS file in production instead of JS code injecting <style>
  173. // tags. If you use code splitting, however, any async bundles will still
  174. // use the "style" loader inside the async code so CSS from them won't be
  175. // in the main CSS file.
  176. {
  177. test: /\.(css|less)$/,
  178. loader: ExtractTextPlugin.extract(
  179. Object.assign(
  180. {
  181. fallback: {
  182. loader: require.resolve('style-loader'),
  183. options: {
  184. hmr: false,
  185. },
  186. },
  187. use: [
  188. {
  189. loader: require.resolve('css-loader'),
  190. options: {
  191. importLoaders: 1,
  192. minimize: true,
  193. sourceMap: shouldUseSourceMap,
  194. },
  195. },
  196. {
  197. loader: require.resolve('less-loader'),
  198. options: {
  199. importLoaders: 1,
  200. minimize: true,
  201. sourceMap: shouldUseSourceMap,
  202. },
  203. },
  204. {
  205. loader: require.resolve('postcss-loader'),
  206. options: {
  207. // Necessary for external CSS imports to work
  208. // https://github.com/facebookincubator/create-react-app/issues/2677
  209. ident: 'postcss',
  210. plugins: () => [
  211. require('postcss-flexbugs-fixes'),
  212. autoprefixer({
  213. browsers: [
  214. '>1%',
  215. 'last 4 versions',
  216. 'Firefox ESR',
  217. 'not ie < 9', // React doesn't support IE8 anyway
  218. ],
  219. flexbox: 'no-2009',
  220. }),
  221. ],
  222. },
  223. },
  224. ],
  225. },
  226. extractTextPluginOptions
  227. )
  228. ),
  229. // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
  230. },
  231. // "file" loader makes sure assets end up in the `build` folder.
  232. // When you `import` an asset, you get its filename.
  233. // This loader doesn't use a "test" so it will catch all modules
  234. // that fall through the other loaders.
  235. {
  236. loader: require.resolve('file-loader'),
  237. // Exclude `js` files to keep "css" loader working as it injects
  238. // it's runtime that would otherwise processed through "file" loader.
  239. // Also exclude `html` and `json` extensions so they get processed
  240. // by webpacks internal loaders.
  241. exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/, /\.(css|less)$/],
  242. options: {
  243. name: 'static/media/[name].[hash:8].[ext]',
  244. },
  245. },
  246. // ** STOP ** Are you adding a new loader?
  247. // Make sure to add the new loader(s) before the "file" loader.
  248. ],
  249. },
  250. ],
  251. },
  252. plugins: [
  253. // Makes some environment variables available in index.html.
  254. // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
  255. // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  256. // In production, it will be an empty string unless you specify "homepage"
  257. // in `package.json`, in which case it will be the pathname of that URL.
  258. new InterpolateHtmlPlugin(env.raw),
  259. // Generates an `index.html` file with the <script> injected.
  260. new HtmlWebpackPlugin({
  261. inject: true,
  262. template: paths.appHtml,
  263. minify: {
  264. removeComments: true,
  265. collapseWhitespace: true,
  266. removeRedundantAttributes: true,
  267. useShortDoctype: true,
  268. removeEmptyAttributes: true,
  269. removeStyleLinkTypeAttributes: true,
  270. keepClosingSlash: true,
  271. minifyJS: true,
  272. minifyCSS: true,
  273. minifyURLs: true,
  274. },
  275. }),
  276. // Makes some environment variables available to the JS code, for example:
  277. // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
  278. // It is absolutely essential that NODE_ENV was set to production here.
  279. // Otherwise React will be compiled in the very slow development mode.
  280. new webpack.DefinePlugin(env.stringified),
  281. // Minify the code.
  282. new UglifyJsPlugin({
  283. uglifyOptions: {
  284. parse: {
  285. // we want uglify-js to parse ecma 8 code. However we want it to output
  286. // ecma 5 compliant code, to avoid issues with older browsers, this is
  287. // whey we put `ecma: 5` to the compress and output section
  288. // https://github.com/facebook/create-react-app/pull/4234
  289. ecma: 8,
  290. },
  291. compress: {
  292. ecma: 5,
  293. warnings: false,
  294. // Disabled because of an issue with Uglify breaking seemingly valid code:
  295. // https://github.com/facebook/create-react-app/issues/2376
  296. // Pending further investigation:
  297. // https://github.com/mishoo/UglifyJS2/issues/2011
  298. comparisons: false,
  299. },
  300. mangle: {
  301. safari10: true,
  302. },
  303. output: {
  304. ecma: 5,
  305. comments: false,
  306. // Turned on because emoji and regex is not minified properly using default
  307. // https://github.com/facebook/create-react-app/issues/2488
  308. ascii_only: true,
  309. },
  310. },
  311. // Use multi-process parallel running to improve the build speed
  312. // Default number of concurrent runs: os.cpus().length - 1
  313. parallel: true,
  314. // Enable file caching
  315. cache: true,
  316. sourceMap: shouldUseSourceMap,
  317. }), // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
  318. new ExtractTextPlugin({
  319. filename: cssFilename,
  320. }),
  321. // Generate a manifest file which contains a mapping of all asset filenames
  322. // to their corresponding output file so that tools can pick it up without
  323. // having to parse `index.html`.
  324. new ManifestPlugin({
  325. fileName: 'asset-manifest.json',
  326. }),
  327. // Generate a service worker script that will precache, and keep up to date,
  328. // the HTML & assets that are part of the Webpack build.
  329. new SWPrecacheWebpackPlugin({
  330. // By default, a cache-busting query parameter is appended to requests
  331. // used to populate the caches, to ensure the responses are fresh.
  332. // If a URL is already hashed by Webpack, then there is no concern
  333. // about it being stale, and the cache-busting can be skipped.
  334. dontCacheBustUrlsMatching: /\.\w{8}\./,
  335. filename: 'service-worker.js',
  336. logger(message) {
  337. if (message.indexOf('Total precache size is') === 0) {
  338. // This message occurs for every build and is a bit too noisy.
  339. return;
  340. }
  341. if (message.indexOf('Skipping static resource') === 0) {
  342. // This message obscures real errors so we ignore it.
  343. // https://github.com/facebookincubator/create-react-app/issues/2612
  344. return;
  345. }
  346. console.log(message);
  347. },
  348. minify: true,
  349. // For unknown URLs, fallback to the index page
  350. navigateFallback: publicUrl + '/index.html',
  351. // Ignores URLs starting from /__ (useful for Firebase):
  352. // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
  353. navigateFallbackWhitelist: [/^(?!\/__).*/],
  354. // Don't precache sourcemaps (they're large) and build asset manifest:
  355. staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
  356. }),
  357. // Moment.js is an extremely popular library that bundles large locale files
  358. // by default due to how Webpack interprets its code. This is a practical
  359. // solution that requires the user to opt into importing specific locales.
  360. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  361. // You can remove this if you don't use Moment.js:
  362. new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  363. // Perform type checking and linting in a separate process to speed up compilation
  364. new ForkTsCheckerWebpackPlugin({
  365. async: false,
  366. tsconfig: paths.appTsProdConfig,
  367. tslint: paths.appTsLint,
  368. }),
  369. ],
  370. // Some libraries import Node modules but don't use them in the browser.
  371. // Tell Webpack to provide empty mocks for them so importing them works.
  372. node: {
  373. dgram: 'empty',
  374. fs: 'empty',
  375. net: 'empty',
  376. tls: 'empty',
  377. child_process: 'empty',
  378. },
  379. };