Update webpack stack
[oweals/peertube.git] / client / config / webpack.common.js
1 const helpers = require('./helpers')
2
3 /*
4  * Webpack Plugins
5  */
6
7 const AssetsPlugin = require('assets-webpack-plugin')
8 const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
9 const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin')
10 const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin')
11 const CopyWebpackPlugin = require('copy-webpack-plugin')
12 const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin
13 const HtmlWebpackPlugin = require('html-webpack-plugin')
14 const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin')
15 const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin')
16 const ngcWebpack = require('ngc-webpack')
17
18 const WebpackNotifierPlugin = require('webpack-notifier')
19
20 /*
21  * Webpack Constants
22  */
23 const METADATA = {
24   title: 'PeerTube',
25   baseUrl: '/',
26   isDevServer: helpers.isWebpackDevServer()
27 }
28
29 /*
30  * Webpack configuration
31  *
32  * See: http://webpack.github.io/docs/configuration.html#cli
33  */
34 module.exports = function (options) {
35   const isProd = options.env === 'production'
36   const AOT = isProd
37
38   return {
39
40     /*
41      * Cache generated modules and chunks to improve performance for multiple incremental builds.
42      * This is enabled by default in watch mode.
43      * You can pass false to disable it.
44      *
45      * See: http://webpack.github.io/docs/configuration.html#cache
46      */
47     // cache: false,
48
49     /*
50      * The entry point for the bundle
51      * Our Angular.js app
52      *
53      * See: http://webpack.github.io/docs/configuration.html#entry
54      */
55     entry: {
56       'polyfills': './src/polyfills.browser.ts',
57       'main': AOT
58               ? './src/main.browser.aot.ts'
59               : './src/main.browser.ts'
60     },
61
62     /*
63      * Options affecting the resolving of modules.
64      *
65      * See: http://webpack.github.io/docs/configuration.html#resolve
66      */
67     resolve: {
68       /*
69        * An array of extensions that should be used to resolve modules.
70        *
71        * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
72        */
73       extensions: [ '.ts', '.js', '.json', '.scss' ],
74
75       modules: [ helpers.root('src'), helpers.root('node_modules') ]
76     },
77
78     /*
79      * Options affecting the normal modules.
80      *
81      * See: http://webpack.github.io/docs/configuration.html#module
82      */
83     module: {
84
85       rules: [
86
87         /*
88          * Typescript loader support for .ts and Angular async routes via .async.ts
89          *
90          * See: https://github.com/s-panferov/awesome-typescript-loader
91          */
92         {
93           test: /\.ts$/,
94           use: [
95             {
96               loader: '@angularclass/hmr-loader',
97               options: {
98                 pretty: !isProd,
99                 prod: isProd
100               }
101             },
102             {
103               loader: 'ng-router-loader',
104               options: {
105                 loader: 'async-import',
106                 genDir: 'compiled',
107                 aot: AOT
108               }
109             },
110             {
111               loader: 'awesome-typescript-loader',
112               options: {
113                 configFileName: 'tsconfig.webpack.json',
114                 useCache: !isProd
115               }
116             },
117             {
118               loader: 'angular2-template-loader'
119             }
120           ],
121           exclude: [/\.(spec|e2e)\.ts$/]
122         },
123
124         /*
125          * Json loader support for *.json files.
126          *
127          * See: https://github.com/webpack/json-loader
128          */
129         {
130           test: /\.json$/,
131           use: 'json-loader'
132         },
133
134         {
135           test: /\.(sass|scss)$/,
136           use: [
137             'css-to-string-loader',
138             'css-loader?sourceMap',
139             'resolve-url-loader',
140             {
141               loader: 'sass-loader',
142               options: {
143                 sourceMap: true
144               }
145             },
146             {
147               loader: 'sass-resources-loader',
148               options: {
149                 resources: [
150                   helpers.root('src/sass/_variables.scss')
151                 ]
152               }
153             }
154           ]
155         },
156         { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'url-loader?limit=10000&minetype=application/font-woff' },
157         { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'file-loader' },
158
159         /* Raw loader support for *.html
160          * Returns file content as string
161          *
162          * See: https://github.com/webpack/raw-loader
163          */
164         {
165           test: /\.html$/,
166           use: 'raw-loader',
167           exclude: [
168             helpers.root('src/index.html'),
169             helpers.root('src/standalone/videos/embed.html')
170           ]
171         },
172
173         /* File loader for supporting images, for example, in CSS files.
174          */
175         {
176           test: /\.(jpg|png|gif)$/,
177           use: 'file-loader'
178         }
179
180       ]
181
182     },
183
184     /*
185      * Add additional plugins to the compiler.
186      *
187      * See: http://webpack.github.io/docs/configuration.html#plugins
188      */
189     plugins: [
190       new AssetsPlugin({
191         path: helpers.root('dist'),
192         filename: 'webpack-assets.json',
193         prettyPrint: true
194       }),
195
196       /*
197        * Plugin: ForkCheckerPlugin
198        * Description: Do type checking in a separate process, so webpack don't need to wait.
199        *
200        * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
201        */
202       new CheckerPlugin(),
203
204       /*
205        * Plugin: CommonsChunkPlugin
206        * Description: Shares common code between the pages.
207        * It identifies common modules and put them into a commons chunk.
208        *
209        * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
210        * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
211        */
212       new CommonsChunkPlugin({
213         name: 'polyfills',
214         chunks: ['polyfills']
215       }),
216
217       // This enables tree shaking of the vendor modules
218       new CommonsChunkPlugin({
219         name: 'vendor',
220         chunks: ['main'],
221         minChunks: module => /node_modules\//.test(module.resource)
222       }),
223
224       // Specify the correct order the scripts will be injected in
225       new CommonsChunkPlugin({
226         name: ['polyfills', 'vendor'].reverse()
227       }),
228
229       /**
230        * Plugin: ContextReplacementPlugin
231        * Description: Provides context to Angular's use of System.import
232        *
233        * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
234        * See: https://github.com/angular/angular/issues/11580
235        */
236       new ContextReplacementPlugin(
237         /**
238          * The (\\|\/) piece accounts for path separators in *nix and Windows
239          */
240         /angular(\\|\/)core(\\|\/)@angular/,
241         helpers.root('src'), // location of your src
242         {
243           /**
244            * Your Angular Async Route paths relative to this root directory
245            */
246         }
247       ),
248
249       /*
250        * Plugin: CopyWebpackPlugin
251        * Description: Copy files and directories in webpack.
252        *
253        * Copies project static assets.
254        *
255        * See: https://www.npmjs.com/package/copy-webpack-plugin
256        */
257       // Used by embed.html
258       new CopyWebpackPlugin([
259         {
260           from: 'src/assets',
261           to: 'assets'
262         },
263         {
264           from: 'node_modules/webtorrent/webtorrent.min.js',
265           to: 'assets/webtorrent'
266         },
267         {
268           from: 'src/standalone',
269           to: 'standalone'
270         }
271       ]),
272
273       /*
274        * Plugin: ScriptExtHtmlWebpackPlugin
275        * Description: Enhances html-webpack-plugin functionality
276        * with different deployment options for your scripts including:
277        *
278        * See: https://github.com/numical/script-ext-html-webpack-plugin
279        */
280       new ScriptExtHtmlWebpackPlugin({
281         sync: [ /polyfill|vendor/ ],
282         defaultAttribute: 'async',
283         preload: [/polyfill|vendor|main/],
284         prefetch: [/chunk/]
285       }),
286
287       /*
288        * Plugin: HtmlWebpackPlugin
289        * Description: Simplifies creation of HTML files to serve your webpack bundles.
290        * This is especially useful for webpack bundles that include a hash in the filename
291        * which changes every compilation.
292        *
293        * See: https://github.com/ampedandwired/html-webpack-plugin
294        */
295       new HtmlWebpackPlugin({
296         template: 'src/index.html',
297         title: METADATA.title,
298         chunksSortMode: 'dependency',
299         metadata: METADATA,
300         inject: 'body'
301       }),
302
303       new WebpackNotifierPlugin({ alwaysNotify: true }),
304
305       /**
306       * Plugin LoaderOptionsPlugin (experimental)
307       *
308       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
309       */
310       new LoaderOptionsPlugin({
311         options: {
312           sassLoader: {
313             precision: 10,
314             includePaths: [ helpers.root('src/sass') ]
315           }
316         }
317       }),
318
319       new ngcWebpack.NgcWebpackPlugin({
320         disabled: !AOT,
321         tsConfig: helpers.root('tsconfig.webpack.json'),
322         resourceOverride: helpers.root('config/resource-override.js')
323       }),
324
325       new BundleAnalyzerPlugin({
326         // Can be `server`, `static` or `disabled`.
327         // In `server` mode analyzer will start HTTP server to show bundle report.
328         // In `static` mode single HTML file with bundle report will be generated.
329         // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
330         analyzerMode: 'static',
331         // Path to bundle report file that will be generated in `static` mode.
332         // Relative to bundles output directory.
333         reportFilename: 'report.html',
334         // Automatically open report in default browser
335         openAnalyzer: false,
336         // If `true`, Webpack Stats JSON file will be generated in bundles output directory
337         generateStatsFile: true,
338         // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
339         // Relative to bundles output directory.
340         statsFilename: 'stats.json',
341         // Options for `stats.toJson()` method.
342         // For example you can exclude sources of your modules from stats file with `source: false` option.
343         // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
344         statsOptions: null,
345         // Log level. Can be 'info', 'warn', 'error' or 'silent'.
346         logLevel: 'info'
347       })
348     ],
349
350     /*
351      * Include polyfills or mocks for various node stuff
352      * Description: Node configuration
353      *
354      * See: https://webpack.github.io/docs/configuration.html#node
355      */
356     node: {
357       global: true,
358       crypto: 'empty',
359       process: true,
360       module: false,
361       clearImmediate: false,
362       setImmediate: false,
363       setInterval: false,
364       setTimeout: false
365     }
366   }
367 }