<commit_before>const helpers = require('./webpack.helpers');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const OptimizeJsPlugin = require('optimize-js-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const { NoEmitOnErrorsPlugin, LoaderOptionsPlugin, ProgressPlugin, ContextReplacementPlugin, NormalModuleReplacementPlugin } = require('webpack');
const { GlobCopyWebpackPlugin, BaseHrefWebpackPlugin } = require('@angular/cli/plugins/webpack');
const { CommonsChunkPlugin, UglifyJsPlugin } = require('webpack').optimize;
const { AotPlugin } = require('@ngtools/webpack');

const srcPath = './src/client';
const distPath = helpers.root('dist', 'wwwroot');
const nodeModules = helpers.root('node_modules');
const entryPoints = ["inline", "polyfills", "sw-register", "styles", "vendor", "main"];

const stats = {
  assets: true,
  cached: false,
  cachedAssets: false,
  children: false,
  chunks: true,
  chunkModules: false,
  chunkOrigins: false,
  colors: true,
  depth: false,
  entrypoints: false,
  errors: true,
  errorDetails: true,
  hash: false,
  maxModules: 0,
  modules: false,
  performance: true,
  providedExports: false,
  publicPath: false,
  reasons: true,
  source: false,
  timings: true,
  usedExports: true,
  version: true,
  warnings: true
};

module.exports = function (args = {}) {
  let isDev = !args.prod;
  let isAot = args.aot;
  let analyze = args.analyze;

  console.log(`WEBPACK ENV: ${JSON.stringify(args)}`);

  return {
    target: 'web',
    devtool: isDev ? 'cheap-module-source-map' : undefined,
    stats: stats,
    entry: {
      'main': helpers.root(srcPath, 'main.ts'),
      'polyfills': helpers.root(srcPath, 'polyfills.ts'),
      'styles': helpers.root(srcPath, 'styles.scss')
    },
    output: {
      path: distPath,
      filename: '[name].bundle.js',
      chunkFilename: '[name].[chunkhash].chunk.js',
    },
    resolve: {
      extensions: ['.ts', '.js', '.json'],
      modules: [helpers.root(srcPath), nodeModules]
    },
    module: {
      rules: [
        {
          enforce: 'pre',
          test: /\.js$/,
          loader: 'source-map-loader',
          exclude: [
            nodeModules
          ]
        },
        {
          test: /\.ts$/,
          use: '@ngtools/webpack'
        },
        {
          exclude: [
            helpers.root(srcPath, 'styles.scss')
          ],
          test: /\.css$/,
          use: [
            'exports-loader?module.exports.toString()',
            'css-loader?{"importLoaders":1}',
            'postcss-loader'
          ]
        },
        {
          exclude: [
            helpers.root(srcPath, 'styles.scss')
          ],
          test: /\.scss$|\.sass$/,
          use: [
            'exports-loader?module.exports.toString()',
            'css-loader?{"importLoaders":1}',
            'postcss-loader',
            'sass-loader'
          ]
        },
        {
          include: [
            helpers.root(srcPath, 'styles.scss')
          ],
          test: /\.css$/,
          use: ExtractTextPlugin.extract({
            use: [
              'css-loader?{"importLoaders":1}',
              'postcss-loader'
            ],
            fallback: 'style-loader',
            publicPath: ''
          })
        },
        {
          include: [
            helpers.root(srcPath, 'styles.scss')
          ],
          test: /\.scss$|\.sass$/,
          use: ExtractTextPlugin.extract({
            use: [
              'css-loader?{"importLoaders":1}',
              'postcss-loader',
              'sass-loader'
            ],
            fallback: 'style-loader',
            publicPath: ''
          })
        },
        {
          test: /\.html$/,
          use: 'raw-loader'
        },
        {
          test: /\.(jpg|png|gif)$/,
          use: 'file-loader'
        },

        {
          test: /\.json$/,
          use: 'json-loader'
        },
        {
          test: /\.(eot|svg)$/,
          use: 'file-loader?name=[name].[hash:20].[ext]'
        },
        {
          test: /\.(jpg|png|gif|otf|ttf|woff|woff2|cur|ani)$/,
          use: 'url-loader?name=[name].[hash:20].[ext]&limit=10000'
        }
      ]
    },
    plugins: (() => {
      var plugins = [
        new CleanWebpackPlugin([distPath], {
          verbose: false
        }),

        new NoEmitOnErrorsPlugin(),
        new GlobCopyWebpackPlugin({
          patterns: [
            'assets',
            'favicon.ico'
          ],
          globOptions: {
            cwd: helpers.root(srcPath),
            dot: true,
            ignore: '**/.gitkeep'
          }
        }),
        new ProgressPlugin(),

        new HtmlWebpackPlugin({
          template: helpers.root(srcPath, 'index.html'),
          filename: './index.html',
          hash: false,
          inject: true,
          compile: true,
          favicon: false,
          minify: false,
          cache: true,
          showErrors: true,
          chunks: 'all',
          excludeChunks: [],
          title: 'Webpack App',
          xhtml: true,
          chunksSortMode: function sort(left, right) {
            let leftIndex = entryPoints.indexOf(left.names[0]);
            let rightindex = entryPoints.indexOf(right.names[0]);
            if (leftIndex > rightindex) {
              return 1;
            }
            else if (leftIndex < rightindex) {
              return -1;
            }
            else {
              return 0;
            }
          }
        }),
        new BaseHrefWebpackPlugin({}),
        new CommonsChunkPlugin({
          name: 'inline',
          minChunks: null
        }),
        new CommonsChunkPlugin({
          name: 'vendor',
          minChunks: (module) => module.resource && module.resource.startsWith(nodeModules),
          chunks: [
            'main'
          ]
        }),
        new ExtractTextPlugin({
          filename: '[name].bundle.css',
          disable: isDev
        }),

        new LoaderOptionsPlugin({
          debug: isDev,
          minimize: !isDev,
          sourceMap: isDev,
          options: {
            sassLoader: {
              sourceMap: isDev,
              includePaths: []
            },
            context: ''
          }
        }),

        new AotPlugin({
          mainPath: 'main.ts',
          exclude: [],
          tsConfigPath: helpers.root(srcPath, 'tsconfig.app.json'),
          skipCodeGeneration: !isAot
        }),

        // Provides context to Angular's use of System.import. See: https://github.com/angular/angular/issues/11580
        new ContextReplacementPlugin(
          /angular(\\|\/)core(\\|\/)@angular/,
          helpers.root(srcPath),
          {
            // your Angular Async Route paths relative to this root directory
          }
        )
      ];

      if (!isDev) {
        plugins = plugins.concat([
          new NormalModuleReplacementPlugin(
            /environment\.ts/,
            'environment.prod.ts'
          ),

          new OptimizeJsPlugin({
            sourceMap: false
          }),

          // Description: Minimize all JavaScript output of chunks.
          // Loaders are switched into minimizing mode.
          // NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
          new UglifyJsPlugin({
            // beautify: true, //debug
            // mangle: false, //debug
            // dead_code: false, //debug
            // unused: false, //debug
            // deadCode: false, //debug
            // compress: {
            //   screw_ie8: true,
            //   keep_fnames: true,
            //   drop_debugger: false,
            //   dead_code: false,
            //   unused: false
            // }, // debug
            // comments: true, //debug

            beautify: false, //prod
            output: {
              comments: false
            }, //prod
            mangle: {
              screw_ie8: true
            }, //prod
            compress: {
              screw_ie8: true,
              warnings: false,
              conditionals: true,
              unused: true,
              comparisons: true,
              sequences: true,
              dead_code: true,
              evaluate: true,
              if_return: true,
              join_vars: true,
              negate_iife: false // we need this for lazy v8
            },
          })
        ]);
      }

      if (analyze) {
        plugins = plugins.concat([
          new BundleAnalyzerPlugin()
        ]);
      }

      return plugins;
    })(),

    node: {
      fs: 'empty',
      global: true,
      crypto: 'empty',
      tls: 'empty',
      net: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    },

    performance: {
      hints: false
    },

    devServer: {
      port: 4200,
      historyApiFallback: true,
      stats: stats
    }
  };
};
<commit_msg>Disable chunks stats<commit_after>const helpers = require('./webpack.helpers');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const OptimizeJsPlugin = require('optimize-js-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const { NoEmitOnErrorsPlugin, LoaderOptionsPlugin, ProgressPlugin, ContextReplacementPlugin, NormalModuleReplacementPlugin } = require('webpack');
const { GlobCopyWebpackPlugin, BaseHrefWebpackPlugin } = require('@angular/cli/plugins/webpack');
const { CommonsChunkPlugin, UglifyJsPlugin } = require('webpack').optimize;
const { AotPlugin } = require('@ngtools/webpack');

const srcPath = './src/client';
const distPath = helpers.root('dist', 'wwwroot');
const nodeModules = helpers.root('node_modules');
const entryPoints = ["inline", "polyfills", "sw-register", "styles", "vendor", "main"];

const stats = {
  assets: true,
  cached: false,
  cachedAssets: false,
  children: false,
  chunks: false,
  chunkModules: false,
  chunkOrigins: false,
  colors: true,
  depth: false,
  entrypoints: false,
  errors: true,
  errorDetails: true,
  hash: false,
  maxModules: 0,
  modules: false,
  performance: true,
  providedExports: false,
  publicPath: false,
  reasons: true,
  source: false,
  timings: true,
  usedExports: true,
  version: true,
  warnings: true
};

module.exports = function (args = {}) {
  let isDev = !args.prod;
  let isAot = args.aot;
  let analyze = args.analyze;

  console.log(`WEBPACK ENV: ${JSON.stringify(args)}`);

  return {
    target: 'web',
    devtool: isDev ? 'cheap-module-source-map' : undefined,
    stats: stats,
    entry: {
      'main': helpers.root(srcPath, 'main.ts'),
      'polyfills': helpers.root(srcPath, 'polyfills.ts'),
      'styles': helpers.root(srcPath, 'styles.scss')
    },
    output: {
      path: distPath,
      filename: '[name].bundle.js',
      chunkFilename: '[name].[chunkhash].chunk.js',
    },
    resolve: {
      extensions: ['.ts', '.js', '.json'],
      modules: [helpers.root(srcPath), nodeModules]
    },
    module: {
      rules: [
        {
          enforce: 'pre',
          test: /\.js$/,
          loader: 'source-map-loader',
          exclude: [
            nodeModules
          ]
        },
        {
          test: /\.ts$/,
          use: '@ngtools/webpack'
        },
        {
          exclude: [
            helpers.root(srcPath, 'styles.scss')
          ],
          test: /\.css$/,
          use: [
            'exports-loader?module.exports.toString()',
            'css-loader?{"importLoaders":1}',
            'postcss-loader'
          ]
        },
        {
          exclude: [
            helpers.root(srcPath, 'styles.scss')
          ],
          test: /\.scss$|\.sass$/,
          use: [
            'exports-loader?module.exports.toString()',
            'css-loader?{"importLoaders":1}',
            'postcss-loader',
            'sass-loader'
          ]
        },
        {
          include: [
            helpers.root(srcPath, 'styles.scss')
          ],
          test: /\.css$/,
          use: ExtractTextPlugin.extract({
            use: [
              'css-loader?{"importLoaders":1}',
              'postcss-loader'
            ],
            fallback: 'style-loader',
            publicPath: ''
          })
        },
        {
          include: [
            helpers.root(srcPath, 'styles.scss')
          ],
          test: /\.scss$|\.sass$/,
          use: ExtractTextPlugin.extract({
            use: [
              'css-loader?{"importLoaders":1}',
              'postcss-loader',
              'sass-loader'
            ],
            fallback: 'style-loader',
            publicPath: ''
          })
        },
        {
          test: /\.html$/,
          use: 'raw-loader'
        },
        {
          test: /\.(jpg|png|gif)$/,
          use: 'file-loader'
        },

        {
          test: /\.json$/,
          use: 'json-loader'
        },
        {
          test: /\.(eot|svg)$/,
          use: 'file-loader?name=[name].[hash:20].[ext]'
        },
        {
          test: /\.(jpg|png|gif|otf|ttf|woff|woff2|cur|ani)$/,
          use: 'url-loader?name=[name].[hash:20].[ext]&limit=10000'
        }
      ]
    },
    plugins: (() => {
      var plugins = [
        new CleanWebpackPlugin([distPath], {
          verbose: false
        }),

        new NoEmitOnErrorsPlugin(),
        new GlobCopyWebpackPlugin({
          patterns: [
            'assets',
            'favicon.ico'
          ],
          globOptions: {
            cwd: helpers.root(srcPath),
            dot: true,
            ignore: '**/.gitkeep'
          }
        }),
        new ProgressPlugin(),

        new HtmlWebpackPlugin({
          template: helpers.root(srcPath, 'index.html'),
          filename: './index.html',
          hash: false,
          inject: true,
          compile: true,
          favicon: false,
          minify: false,
          cache: true,
          showErrors: true,
          chunks: 'all',
          excludeChunks: [],
          title: 'Webpack App',
          xhtml: true,
          chunksSortMode: function sort(left, right) {
            let leftIndex = entryPoints.indexOf(left.names[0]);
            let rightindex = entryPoints.indexOf(right.names[0]);
            if (leftIndex > rightindex) {
              return 1;
            }
            else if (leftIndex < rightindex) {
              return -1;
            }
            else {
              return 0;
            }
          }
        }),
        new BaseHrefWebpackPlugin({}),
        new CommonsChunkPlugin({
          name: 'inline',
          minChunks: null
        }),
        new CommonsChunkPlugin({
          name: 'vendor',
          minChunks: (module) => module.resource && module.resource.startsWith(nodeModules),
          chunks: [
            'main'
          ]
        }),
        new ExtractTextPlugin({
          filename: '[name].bundle.css',
          disable: isDev
        }),

        new LoaderOptionsPlugin({
          debug: isDev,
          minimize: !isDev,
          sourceMap: isDev,
          options: {
            sassLoader: {
              sourceMap: isDev,
              includePaths: []
            },
            context: ''
          }
        }),

        new AotPlugin({
          mainPath: 'main.ts',
          exclude: [],
          tsConfigPath: helpers.root(srcPath, 'tsconfig.app.json'),
          skipCodeGeneration: !isAot
        }),

        // Provides context to Angular's use of System.import. See: https://github.com/angular/angular/issues/11580
        new ContextReplacementPlugin(
          /angular(\\|\/)core(\\|\/)@angular/,
          helpers.root(srcPath),
          {
            // your Angular Async Route paths relative to this root directory
          }
        )
      ];

      if (!isDev) {
        plugins = plugins.concat([
          new NormalModuleReplacementPlugin(
            /environment\.ts/,
            'environment.prod.ts'
          ),

          new OptimizeJsPlugin({
            sourceMap: false
          }),

          // Description: Minimize all JavaScript output of chunks.
          // Loaders are switched into minimizing mode.
          // NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
          new UglifyJsPlugin({
            // beautify: true, //debug
            // mangle: false, //debug
            // dead_code: false, //debug
            // unused: false, //debug
            // deadCode: false, //debug
            // compress: {
            //   screw_ie8: true,
            //   keep_fnames: true,
            //   drop_debugger: false,
            //   dead_code: false,
            //   unused: false
            // }, // debug
            // comments: true, //debug

            beautify: false, //prod
            output: {
              comments: false
            }, //prod
            mangle: {
              screw_ie8: true
            }, //prod
            compress: {
              screw_ie8: true,
              warnings: false,
              conditionals: true,
              unused: true,
              comparisons: true,
              sequences: true,
              dead_code: true,
              evaluate: true,
              if_return: true,
              join_vars: true,
              negate_iife: false // we need this for lazy v8
            },
          })
        ]);
      }

      if (analyze) {
        plugins = plugins.concat([
          new BundleAnalyzerPlugin()
        ]);
      }

      return plugins;
    })(),

    node: {
      fs: 'empty',
      global: true,
      crypto: 'empty',
      tls: 'empty',
      net: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    },

    performance: {
      hints: false
    },

    devServer: {
      port: 4200,
      historyApiFallback: true,
      stats: stats
    }
  };
};
<|endoftext|>


<commit_before>const webpack = require("webpack");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
var path = require("path");
var plugins = [];
const production = process.env.NODE_ENV === "production";

//do we minify it all
if (production) {
	console.log("creating production build");
	plugins.push(
		new webpack.DefinePlugin({
			"process.env.NODE_ENV": '"production"'
		})
	);
}

/**
 * @author Dylan Vorster
 */
module.exports =
	//for building the umd distribution
	{
		entry: "./src/main.ts",
		output: {
			filename: "main.js",
			path: __dirname + "/dist",
			libraryTarget: "umd",
			library: "storm-react-diagrams"
		},
		externals: {
			react: {
				root: "React",
				commonjs2: "react",
				commonjs: "react",
				amd: "react"
			},
			"react-dom": {
				root: "ReactDOM",
				commonjs2: "react-dom",
				commonjs: "react-dom",
				amd: "react-dom"
			},
			lodash: {
				commonjs: "lodash",
				commonjs2: "lodash",
				amd: "_",
				root: "_"
			}
		},
		plugins: plugins,
		module: {
			rules: [
				{
					enforce: "pre",
					test: /\.js$/,
					loader: "source-map-loader"
				},
				{
					test: /\.tsx?$/,
					loader: "awesome-typescript-loader"
				}
			]
		},
		resolve: {
			extensions: [".tsx", ".ts", ".js"]
		},
		devtool: production ? "source-map" : "cheap-module-source-map",
		mode: production ? "production" : "development",
		optimization: {
			minimizer: [
				// we specify a custom UglifyJsPlugin here to get source maps in production
				new UglifyJsPlugin({
					uglifyOptions: {
						compress: false,
						ecma: 6,
						mangle: false
					},
					sourceMap: true
				})
			]
		}
	};
<commit_msg>Change UglifyJsPlugin's ECMAScript target version to 5<commit_after>const webpack = require("webpack");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
var path = require("path");
var plugins = [];
const production = process.env.NODE_ENV === "production";

//do we minify it all
if (production) {
	console.log("creating production build");
	plugins.push(
		new webpack.DefinePlugin({
			"process.env.NODE_ENV": '"production"'
		})
	);
}

/**
 * @author Dylan Vorster
 */
module.exports =
	//for building the umd distribution
	{
		entry: "./src/main.ts",
		output: {
			filename: "main.js",
			path: __dirname + "/dist",
			libraryTarget: "umd",
			library: "storm-react-diagrams"
		},
		externals: {
			react: {
				root: "React",
				commonjs2: "react",
				commonjs: "react",
				amd: "react"
			},
			"react-dom": {
				root: "ReactDOM",
				commonjs2: "react-dom",
				commonjs: "react-dom",
				amd: "react-dom"
			},
			lodash: {
				commonjs: "lodash",
				commonjs2: "lodash",
				amd: "_",
				root: "_"
			}
		},
		plugins: plugins,
		module: {
			rules: [
				{
					enforce: "pre",
					test: /\.js$/,
					loader: "source-map-loader"
				},
				{
					test: /\.tsx?$/,
					loader: "awesome-typescript-loader"
				}
			]
		},
		resolve: {
			extensions: [".tsx", ".ts", ".js"]
		},
		devtool: production ? "source-map" : "cheap-module-source-map",
		mode: production ? "production" : "development",
		optimization: {
			minimizer: [
				// we specify a custom UglifyJsPlugin here to get source maps in production
				new UglifyJsPlugin({
					uglifyOptions: {
						compress: false,
						ecma: 5,
						mangle: false
					},
					sourceMap: true
				})
			]
		}
	};
<|endoftext|>


<commit_before>let path = require('path'),
    webpack = require("webpack");

module.exports = {
    entry: {
        testModule: 'testModule.js'
    },

    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, "public", "javascripts")
    },

    resolve: {
        modules: [
            path.join(__dirname, "frontend"),
            "node_modules"
        ]
    },

    module: {
        rules: [
            /*{
                test: require.resolve("whatwg-fetch"),
                use: 'imports?this=>global!exports?fetch=global.fetch'
            },*/
            {
                test: /\.js$/,
                use: [
                    {
                        loader: "babel-loader",
                        options: {
                            presets: ['es2017'],
                            plugins: ["transform-runtime"]
                        }
                    }
                ],
                exclude: [/node_modules/]
            }
        ]
    },

    plugins: [
        // new webpack.HotModuleReplacementPlugin(),
        new webpack.ProvidePlugin({
            // 'Promise': 'es6-promise', // Thanks Aaron (https://gist.github.com/Couto/b29676dd1ab8714a818f#gistcomment-1584602)
            // 'fetch': 'whatwg-fetch'
        }),
        //new webpack.optimize.CommonsChunkPlugin('app', null, false),
        // new webpack.NoEmitOnErrorsPlugin(),
        // new HtmlWebpackPlugin({
        //     template: path.resolve('./', 'index.html'),
        //     webpackDevServer: '/webpack-dev-server.js'
        // })
    ],

    // watch: true,
    // watchOptions: {
    //     aggregateTimeout: 100
    // },

    devtool: "source-map"
};<commit_msg>added babel<commit_after>let path = require('path'),
    webpack = require("webpack");

module.exports = {
    entry: {
        testModule: 'testModule.js'
    },

    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, "public", "javascripts")
    },

    resolve: {
        modules: [
            path.join(__dirname, "frontend"),
            "node_modules"
        ]
    },

    module: {
        rules: [
            /*{
                test: require.resolve("whatwg-fetch"),
                use: 'imports?this=>global!exports?fetch=global.fetch'
            },*/
            {
                test: /\.js$/,
                use: [
                    {
                        loader: "babel-loader",
                        options: {
                            presets: ['es2015'],
                            plugins: ["transform-runtime"]
                        }
                    }
                ],
                exclude: [/node_modules/]
            }
        ]
    },

    plugins: [
        // new webpack.HotModuleReplacementPlugin(),
        new webpack.ProvidePlugin({
            // 'Promise': 'es6-promise', // Thanks Aaron (https://gist.github.com/Couto/b29676dd1ab8714a818f#gistcomment-1584602)
            // 'fetch': 'whatwg-fetch'
        }),
        //new webpack.optimize.CommonsChunkPlugin('app', null, false),
        // new webpack.NoEmitOnErrorsPlugin(),
        // new HtmlWebpackPlugin({
        //     template: path.resolve('./', 'index.html'),
        //     webpackDevServer: '/webpack-dev-server.js'
        // })
    ],

    // watch: true,
    // watchOptions: {
    //     aggregateTimeout: 100
    // },

    devtool: "source-map"
};<|endoftext|>


<commit_before>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2015, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */

(function(Utils, VFS, API) {
  'use strict';

  window.OSjs       = window.OSjs       || {};
  OSjs.Helpers      = OSjs.Helpers      || {};

  function format(fmt, date) {
    var utc = undefined;

    if ( typeof fmt !== 'string' ) {
      utc = fmt.utc;
      fmt = fmt.format;
    } else {
      utc = ExtendedDate.config.utc;
    }

    if ( date instanceof ExtendedDate ) {
      date = date.date;
    }
    return dateFormat(date, fmt, utc);
  }

  /////////////////////////////////////////////////////////////////////////////
  // EXTENDED DATE FUNCTIONS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Extended Date Helper
   *
   * Works just like 'Date', but has some extended methods
   *
   * @api OSjs.Helpers.Date
   * @extends Date
   * @see Date
   * @class
   */
  function ExtendedDate(date) {
    if ( date ) {
      if ( date instanceof Date ) {
        this.date = date;
        return;
      } else if ( date instanceof ExtendedDate ) {
        this.date = date.date;
        return;
      }
    }
    this.date = new Date();
    /*
    function construct(constructor, args) {
      function F() {
        return constructor.apply(this, args);
      }
      F.prototype = constructor.prototype;
      return new F();
    }

    this.date = construct(Date, arguments);
    */
  }

  //
  // Global Configuration
  //
  ExtendedDate.config = {
    utc: true
  };

  //
  // Extended Methods
  //

  ExtendedDate.prototype.format = function(fmt) {
    return ExtendedDate.format(this.date, fmt);
  };

  ExtendedDate.prototype.getFirstDayInMonth = function(fmt) {
    return ExtendedDate.getFirstDayInMonth(fmt, null, null, this.date);
  };

  ExtendedDate.prototype.getLastDayInMonth = function(fmt) {
    return ExtendedDate.getLastDayInMonth(fmt, null, null, this.date);
  };

  ExtendedDate.prototype.getDaysInMonth = function() {
    return ExtendedDate.getDaysInMonth(null, null, this.date);
  };

  ExtendedDate.prototype.getWeekNumber = function() {
    return ExtendedDate.getWeekNumber(this.date);
  };

  //
  // Static Methods
  //

  ExtendedDate.format = function(date, fmt) {
    return format(fmt, date);
  };

  ExtendedDate.getPreviousMonth = function() {
    var now = new Date();
    var current;

    if (now.getMonth() == 0) {
      current = new Date(now.getFullYear() - 1, 11, 1);
    } else {
      current = new Date(now.getFullYear(), now.getMonth() - 1, 1);
    }

    return new ExtendedDate(current);
  };

  ExtendedDate.getNextMonth = function() {
    var now = new Date();
    var current;

    if (now.getMonth() == 11) {
      current = new Date(now.getFullYear() + 1, 0, 1);
    } else {
      current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
    }

    return new ExtendedDate(current);
  };

  ExtendedDate.getFirstDayInMonth = function(fmt, y, m, now) {
    now = now ? (now instanceof ExtendedDate ? now.date : now) : new Date();
    y = (typeof y === 'undefined' || y === null || y < 0 ) ? now.getFullYear() : y;
    m = (typeof m === 'undefined' || m === null || m < 0 ) ? now.getMonth() : m;

    var date = new Date();
    date.setFullYear(y, m, 1);
    if ( fmt === true ) {
      return date.getDate();
    }
    return fmt ? format(fmt, date) : new ExtendedDate(date);
  };

  ExtendedDate.getLastDayInMonth = function(fmt, y, m, now) {
    now = now ? (now instanceof ExtendedDate ? now.date : now) : new Date();
    y = (typeof y === 'undefined' || y === null || y < 0 ) ? now.getFullYear() : y;
    m = (typeof m === 'undefined' || m === null || m < 0 ) ? now.getMonth() : m;

    var date = new Date();
    date.setFullYear(y, m, 0);
    if ( fmt === true ) {
      return date.getDate();
    }
    return fmt ? format(fmt, date) : new ExtendedDate(date);
  };

  ExtendedDate.getDaysInMonth = function(y, m, now) {
    now = now ? (now instanceof ExtendedDate ? now.date : now) : new Date();
    y = (typeof y === 'undefined' || y === null || y < 0 ) ? now.getFullYear() : y;
    m = (typeof m === 'undefined' || m === null || m < 0 ) ? now.getMonth() : m;

    var date = new Date();
    date.setFullYear(y, m, 0);
    return parseInt(date.getDate(), 10);
  };

  ExtendedDate.getWeekNumber = function(now) {
    now = now ? (now instanceof ExtendedDate ? now.date : now) : new Date();

    var d = new Date(+now);
    d.setHours(0,0,0);
    d.setDate(d.getDate()+4-(d.getDay()||7));
    return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);

  };

  /////////////////////////////////////////////////////////////////////////////
  // DATE FORMATTING
  /////////////////////////////////////////////////////////////////////////////

  /*
   * Date Format 1.2.3
   * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
   * MIT license
   *
   * Includes enhancements by Scott Trenda <scott.trenda.net>
   * and Kris Kowal <cixar.com/~kris.kowal/>
   */
  var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g;

    function pad(val, len) {
      val = String(val);
      len = len || 2;
      while (val.length < len) {
        val = '0' + val;
      }
      return val;
    }

    return function (date, mask, utc) {
      var dF = dateFormat;

      if (arguments.length == 1 && Object.prototype.toString.call(date) == '[object String]' && !/\d/.test(date)) {
        mask = date;
        date = undefined;
      }

      date = date ? new Date(date) : new Date;
      if (isNaN(date)) throw SyntaxError('invalid date');

      mask = String(dF.masks[mask] || mask || dF.masks['default']);
      if (mask.slice(0, 4) == 'UTC:') {
        mask = mask.slice(4);
        utc = true;
      }

      var _ = utc ? 'getUTC' : 'get',
        d = date[_ + 'Date'](),
        D = date[_ + 'Day'](),
        m = date[_ + 'Month'](),
        y = date[_ + 'FullYear'](),
        H = date[_ + 'Hours'](),
        M = date[_ + 'Minutes'](),
        s = date[_ + 'Seconds'](),
        L = date[_ + 'Milliseconds'](),
        o = utc ? 0 : date.getTimezoneOffset(),
        flags = {
          d:    d,
          dd:   pad(d),
          ddd:  dF.i18n.dayNames[D],
          dddd: dF.i18n.dayNames[D + 7],
          m:    m + 1,
          mm:   pad(m + 1),
          mmm:  dF.i18n.monthNames[m],
          mmmm: dF.i18n.monthNames[m + 12],
          yy:   String(y).slice(2),
          yyyy: y,
          h:    H % 12 || 12,
          hh:   pad(H % 12 || 12),
          H:    H,
          HH:   pad(H),
          M:    M,
          MM:   pad(M),
          s:    s,
          ss:   pad(s),
          l:    pad(L, 3),
          L:    pad(L > 99 ? Math.round(L / 10) : L),
          t:    H < 12 ? 'a'  : 'p',
          tt:   H < 12 ? 'am' : 'pm',
          T:    H < 12 ? 'A'  : 'P',
          TT:   H < 12 ? 'AM' : 'PM',
          Z:    utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''),
          o:    (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
          S:    ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
        };

      return mask.replace(token, function ($0) {
        return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
      });
    };
  }();

  dateFormat.masks = {
    'default':      'ddd mmm dd yyyy HH:MM:ss',
    shortDate:      'm/d/yy',
    mediumDate:     'mmm d, yyyy',
    longDate:       'mmmm d, yyyy',
    fullDate:       'dddd, mmmm d, yyyy',
    shortTime:      'h:MM TT',
    mediumTime:     'h:MM:ss TT',
    longTime:       'h:MM:ss TT Z',
    isoDate:        'yyyy-mm-dd',
    isoTime:        'HH:MM:ss',
    isoDateTime:    'yyyy-mm-dd\'T\'HH:MM:ss',
    isoUtcDateTime: 'UTC:yyyy-mm-dd\'T\'HH:MM:ss\'Z\''
  };

  dateFormat.i18n = {
    dayNames: [
      'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
      'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
    ],
    monthNames: [
      'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
      'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'
    ]
  };

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.Helpers.Date = ExtendedDate;

})(OSjs.Utils, OSjs.VFS, OSjs.API);

<commit_msg>Date: Updated<commit_after>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2015, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */

(function(Utils, VFS, API) {
  'use strict';

  window.OSjs       = window.OSjs       || {};
  OSjs.Helpers      = OSjs.Helpers      || {};

  function filter(from, index, shrt, toindex) {
    var list = [];
    for ( var i = (shrt ? 0 : toindex); i < from.length; i++ ) {
      list.push(from[i]);
    }
    return list;
  }

  function format(fmt, date) {
    var utc = undefined;

    if ( typeof fmt !== 'string' ) {
      utc = fmt.utc;
      fmt = fmt.format;
    } else {
      utc = ExtendedDate.config.utc;
    }

    if ( date instanceof ExtendedDate ) {
      date = date.date;
    }
    return dateFormat(date, fmt, utc);
  }

  /////////////////////////////////////////////////////////////////////////////
  // EXTENDED DATE FUNCTIONS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Extended Date Helper
   *
   * Works just like 'Date', but has some extended methods
   *
   * @api OSjs.Helpers.Date
   * @extends Date
   * @see Date
   * @class
   */
  function ExtendedDate(date) {
    if ( date ) {
      if ( date instanceof Date ) {
        this.date = date;
        return;
      } else if ( date instanceof ExtendedDate ) {
        this.date = date.date;
        return;
      }
    }
    this.date = new Date();
    /*
    function construct(constructor, args) {
      function F() {
        return constructor.apply(this, args);
      }
      F.prototype = constructor.prototype;
      return new F();
    }

    this.date = construct(Date, arguments);
    */
  }

  //
  // Global Configuration
  //
  ExtendedDate.config = {
    //utc: true
  };

  //
  // Extended Methods
  //

  ExtendedDate.prototype.format = function(fmt) {
    return ExtendedDate.format(this.date, fmt);
  };

  ExtendedDate.prototype.getFirstDayInMonth = function(fmt) {
    return ExtendedDate.getFirstDayInMonth(fmt, null, null, this.date);
  };

  ExtendedDate.prototype.getLastDayInMonth = function(fmt) {
    return ExtendedDate.getLastDayInMonth(fmt, null, null, this.date);
  };

  ExtendedDate.prototype.getDaysInMonth = function() {
    return ExtendedDate.getDaysInMonth(null, null, this.date);
  };

  ExtendedDate.prototype.getWeekNumber = function() {
    return ExtendedDate.getWeekNumber(this.date);
  };

  //
  // Static Methods
  //

  ExtendedDate.format = function(date, fmt) {
    return format(fmt, date);
  };

  ExtendedDate.getPreviousMonth = function(now) {
    now = now ? (now instanceof ExtendedDate ? now.date : now) : new Date();
    var current;

    if (now.getMonth() == 0) {
      current = new Date(now.getFullYear() - 1, 11, 1);
    } else {
      current = new Date(now.getFullYear(), now.getMonth() - 1, 1);
    }

    return new ExtendedDate(current);
  };

  ExtendedDate.getNextMonth = function(now) {
    now = now ? (now instanceof ExtendedDate ? now.date : now) : new Date();
    var current;

    if (now.getMonth() == 11) {
      current = new Date(now.getFullYear() + 1, 0, 1);
    } else {
      current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
    }

    return new ExtendedDate(current);
  };

  ExtendedDate.getFirstDayInMonth = function(fmt, y, m, now) {
    now = now ? (now instanceof ExtendedDate ? now.date : now) : new Date();
    y = (typeof y === 'undefined' || y === null || y < 0 ) ? now.getFullYear() : y;
    m = (typeof m === 'undefined' || m === null || m < 0 ) ? now.getMonth() : m;

    var date = new Date();
    date.setFullYear(y, m, 1);
    if ( fmt === true ) {
      return date.getDate();
    }
    return fmt ? format(fmt, date) : new ExtendedDate(date);
  };

  ExtendedDate.getLastDayInMonth = function(fmt, y, m, now) {
    now = now ? (now instanceof ExtendedDate ? now.date : now) : new Date();
    y = (typeof y === 'undefined' || y === null || y < 0 ) ? now.getFullYear() : y;
    m = (typeof m === 'undefined' || m === null || m < 0 ) ? now.getMonth() : m;

    var date = new Date();
    date.setFullYear(y, m, 0);
    if ( fmt === true ) {
      return date.getDate();
    }
    return fmt ? format(fmt, date) : new ExtendedDate(date);
  };

  ExtendedDate.getDaysInMonth = function(y, m, now) {
    now = now ? (now instanceof ExtendedDate ? now.date : now) : new Date();
    y = (typeof y === 'undefined' || y === null || y < 0 ) ? now.getFullYear() : y;
    m = (typeof m === 'undefined' || m === null || m < 0 ) ? now.getMonth() : m;

    var date = new Date();
    date.setFullYear(y, m, 0);
    return parseInt(date.getDate(), 10);
  };

  ExtendedDate.getWeekNumber = function(now) {
    now = now ? (now instanceof ExtendedDate ? now.date : now) : new Date();

    var d = new Date(+now);
    d.setHours(0,0,0);
    d.setDate(d.getDate()+4-(d.getDay()||7));
    return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
  };

  ExtendedDate.getDayName = function(index, shrt) {
    if ( index < 0 || index === null || typeof index === 'undefined' ) {
      return filter(dateFormat.i18n.dayNames, index, shrt, 7);
    }

    shrt = shrt ? 0 : 1;
    var idx = index + (shrt + 7);
    return dateFormat.dayNames[idx];
  };

  ExtendedDate.getMonthName = function(index, shrt) {
    if ( index < 0 || index === null || typeof index === 'undefined' ) {
      return filter(dateFormat.i18n.monthNames, index, shrt, 12);
    }

    shrt = shrt ? 0 : 1;
    var idx = index + (shrt + 12);
    return dateFormat.monthNames[idx];
  };

  /////////////////////////////////////////////////////////////////////////////
  // DATE FORMATTING
  /////////////////////////////////////////////////////////////////////////////

  /*
   * Date Format 1.2.3
   * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
   * MIT license
   *
   * Includes enhancements by Scott Trenda <scott.trenda.net>
   * and Kris Kowal <cixar.com/~kris.kowal/>
   */
  var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g;

    function pad(val, len) {
      val = String(val);
      len = len || 2;
      while (val.length < len) {
        val = '0' + val;
      }
      return val;
    }

    return function (date, mask, utc) {
      var dF = dateFormat;

      if (arguments.length == 1 && Object.prototype.toString.call(date) == '[object String]' && !/\d/.test(date)) {
        mask = date;
        date = undefined;
      }

      date = date ? new Date(date) : new Date;
      if (isNaN(date)) throw SyntaxError('invalid date');

      mask = String(dF.masks[mask] || mask || dF.masks['default']);
      if (mask.slice(0, 4) == 'UTC:') {
        mask = mask.slice(4);
        utc = true;
      }

      var _ = utc ? 'getUTC' : 'get',
        d = date[_ + 'Date'](),
        D = date[_ + 'Day'](),
        m = date[_ + 'Month'](),
        y = date[_ + 'FullYear'](),
        H = date[_ + 'Hours'](),
        M = date[_ + 'Minutes'](),
        s = date[_ + 'Seconds'](),
        L = date[_ + 'Milliseconds'](),
        o = utc ? 0 : date.getTimezoneOffset(),
        flags = {
          d:    d,
          dd:   pad(d),
          ddd:  dF.i18n.dayNames[D],
          dddd: dF.i18n.dayNames[D + 7],
          m:    m + 1,
          mm:   pad(m + 1),
          mmm:  dF.i18n.monthNames[m],
          mmmm: dF.i18n.monthNames[m + 12],
          yy:   String(y).slice(2),
          yyyy: y,
          h:    H % 12 || 12,
          hh:   pad(H % 12 || 12),
          H:    H,
          HH:   pad(H),
          M:    M,
          MM:   pad(M),
          s:    s,
          ss:   pad(s),
          l:    pad(L, 3),
          L:    pad(L > 99 ? Math.round(L / 10) : L),
          t:    H < 12 ? 'a'  : 'p',
          tt:   H < 12 ? 'am' : 'pm',
          T:    H < 12 ? 'A'  : 'P',
          TT:   H < 12 ? 'AM' : 'PM',
          Z:    utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''),
          o:    (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
          S:    ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
        };

      return mask.replace(token, function ($0) {
        return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
      });
    };
  }();

  dateFormat.masks = {
    'default':      'ddd mmm dd yyyy HH:MM:ss',
    shortDate:      'm/d/yy',
    mediumDate:     'mmm d, yyyy',
    longDate:       'mmmm d, yyyy',
    fullDate:       'dddd, mmmm d, yyyy',
    shortTime:      'h:MM TT',
    mediumTime:     'h:MM:ss TT',
    longTime:       'h:MM:ss TT Z',
    isoDate:        'yyyy-mm-dd',
    isoTime:        'HH:MM:ss',
    isoDateTime:    'yyyy-mm-dd\'T\'HH:MM:ss',
    isoUtcDateTime: 'UTC:yyyy-mm-dd\'T\'HH:MM:ss\'Z\''
  };

  dateFormat.i18n = {
    dayNames: [
      'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
      'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
    ],
    monthNames: [
      'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
      'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'
    ]
  };

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.Helpers.Date = ExtendedDate;

})(OSjs.Utils, OSjs.VFS, OSjs.API);

<|endoftext|>


<commit_before>const path = require('path')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    library: 'printJS',
    libraryTarget: 'umd',
    path: path.resolve(__dirname, 'dist'),
    filename: 'print.js',
    sourceMapFilename: 'print.map',
    libraryExport: 'default'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      },
      // TODO: Configure istanbul to interpret how webpack bundles files
      // {
      //   test: /\.js$/,
      //   use: {
      //     loader: 'istanbul-instrumenter-loader',
      //     options: { esModules: true }
      //   },
      //   enforce: 'post',
      //   exclude: /node_modules|\.spec\.js$/
      // },
      {
        test: /\.scss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'css-loader',
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'print.css'
    })
  ],
  optimization: {
    minimizer: [
      new OptimizeCssAssetsPlugin({
        assetNameRegExp: /\.css$/g,
        canPrint: false
      }),
      new UglifyJSPlugin({
        sourceMap: true
      })
    ]
  }
}
<commit_msg>add default development mode to webpack config<commit_after>const path = require('path')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')

module.exports = {
  mode: "development",
  entry: [
    './src/index.js'
  ],
  output: {
    library: 'printJS',
    libraryTarget: 'umd',
    path: path.resolve(__dirname, 'dist'),
    filename: 'print.js',
    sourceMapFilename: 'print.map',
    libraryExport: 'default'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      },
      // TODO: Configure istanbul to interpret how webpack bundles files
      // {
      //   test: /\.js$/,
      //   use: {
      //     loader: 'istanbul-instrumenter-loader',
      //     options: { esModules: true }
      //   },
      //   enforce: 'post',
      //   exclude: /node_modules|\.spec\.js$/
      // },
      {
        test: /\.scss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'css-loader',
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'print.css'
    })
  ],
  optimization: {
    minimizer: [
      new OptimizeCssAssetsPlugin({
        assetNameRegExp: /\.css$/g,
        canPrint: false
      }),
      new UglifyJSPlugin({
        sourceMap: true
      })
    ]
  }
}
<|endoftext|>


<commit_before>ngapp.config(['$stateProvider', function ($stateProvider) {
    $stateProvider.state('base.start', {
        templateUrl: 'partials/start.html',
        controller: 'startController',
        url: '/start'
    });
}]);

ngapp.controller('startController', function ($scope, $rootScope, profileService, settingsService, appModeService, xelibService) {
    // initialization
    profileService.validateProfiles();
    $scope.profiles = profileService.profiles;
    $scope.appModes = appModeService.applicationModes;
    $scope.selectedProfile = profileService.getDefaultProfile();
    $scope.selectedAppMode = $scope.appModes[0];

    // scope functions
    $scope.getLoadOrder = function () {
        let loadOrder = xelib.GetLoadOrder().split('\r\n');
        let activePlugins = xelib.GetActivePlugins().split('\r\n');
        console.log('Load Order:\n' + loadOrder);
        console.log('Active Plugins:\n' + activePlugins);
        return loadOrder.map(function(filename) {
            let handle = xelib.LoadPluginHeader(filename);
            try {
                return {
                    filename: filename,
                    masterNames: xelib.GetMasterNames(handle),
                    active: activePlugins.includes(filename)
                }
            } finally {
                xelib.UnloadPlugin(handle);
            }
        })
    };

    $scope.checkHardcodedDat = function() {
        let game = profileService.getGame($scope.selectedProfile.gameMode);
        let fileName = game.shortName + '.Hardcoded.dat';
        if (fh.jetpack.exists(fileName)) return true;
        alert(`Error: Required file "${fileName}" not found, please re-install the application.`);
    };

    $scope.startSession = function () {
        if (!$scope.checkHardcodedDat()) return;
        $rootScope.profile = $scope.selectedProfile;
        $rootScope.appMode = $scope.selectedAppMode;
        settingsService.loadProfileSettings($scope.selectedProfile.name);
        xelibService.startSession($scope.selectedProfile);
        $scope.$emit('setTitle', 'zEdit - Selecting Load Order');
        $scope.$emit('sessionStarted', $scope.selectedProfile);
        $scope.$emit('openModal', 'loadOrder', {
            loadOrder: $scope.getLoadOrder()
        });
    };

    // event listeners
    $scope.$on('settingsClick', function() {
        if ($rootScope.profile) return;
        $scope.$emit('openModal', 'profiles');
    });

    $scope.$on('profilesUpdated', function() {
        $scope.selectedProfile = profileService.getDefaultProfile();
    });
});
<commit_msg>fixed issue with ESL files breaking the load order modal<commit_after>ngapp.config(['$stateProvider', function ($stateProvider) {
    $stateProvider.state('base.start', {
        templateUrl: 'partials/start.html',
        controller: 'startController',
        url: '/start'
    });
}]);

ngapp.controller('startController', function ($scope, $rootScope, profileService, settingsService, appModeService, xelibService) {
    // initialization
    profileService.validateProfiles();
    $scope.profiles = profileService.profiles;
    $scope.appModes = appModeService.applicationModes;
    $scope.selectedProfile = profileService.getDefaultProfile();
    $scope.selectedAppMode = $scope.appModes[0];

    // helper functions
    let getMasterNames = function(filename) {
        let handle;
        try {
            handle = xelib.LoadPluginHeader(filename);
            return xelib.GetMasterNames(handle);
        } catch(x) {
            console.log(x);
        } finally {
            xelib.UnloadPlugin(handle);
        }
    };

    // scope functions
    $scope.getLoadOrder = function () {
        let loadOrder = xelib.GetLoadOrder().split('\r\n');
        let activePlugins = xelib.GetActivePlugins().split('\r\n');
        console.log('Load Order:\n' + loadOrder);
        console.log('Active Plugins:\n' + activePlugins);
        return loadOrder.map(function(filename) {
            return {
                filename: filename,
                masterNames: getMasterNames(filename) || [],
                active: activePlugins.includes(filename)
            }
        })
    };

    $scope.checkHardcodedDat = function() {
        let game = profileService.getGame($scope.selectedProfile.gameMode);
        let fileName = game.shortName + '.Hardcoded.dat';
        if (fh.jetpack.exists(fileName)) return true;
        alert(`Error: Required file "${fileName}" not found, please re-install the application.`);
    };

    $scope.startSession = function () {
        if (!$scope.checkHardcodedDat()) return;
        $rootScope.profile = $scope.selectedProfile;
        $rootScope.appMode = $scope.selectedAppMode;
        settingsService.loadProfileSettings($scope.selectedProfile.name);
        xelibService.startSession($scope.selectedProfile);
        $scope.$emit('setTitle', 'zEdit - Selecting Load Order');
        $scope.$emit('sessionStarted', $scope.selectedProfile);
        $scope.$emit('openModal', 'loadOrder', {
            loadOrder: $scope.getLoadOrder()
        });
    };

    // event listeners
    $scope.$on('settingsClick', function() {
        if ($rootScope.profile) return;
        $scope.$emit('openModal', 'profiles');
    });

    $scope.$on('profilesUpdated', function() {
        $scope.selectedProfile = profileService.getDefaultProfile();
    });
});
<|endoftext|>


<commit_before>var config = {
  entry: './src/example/main.js',
  output: {
    path: __dirname+'/build/example',
    filename: 'main.js'
  },
  module: {
    loaders: [
      {
        test: /\.js?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {
          optional: ['runtime'],
          stage: 0
        }
      }
    ]
  }
};

module.exports = config;<commit_msg>adjust webpack dev server pooling deplay<commit_after>var config = {
  entry: './src/example/main.js',
  output: {
    path: `${__dirname}/build/example`,
    filename: 'main.js'
  },
  module: {
    loaders: [
      {
        test: /\.js?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {
          optional: ['runtime'],
          stage: 0
        }
      }
    ]
  },
  devServer: {
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    watchOptions: {
      aggregateTimeout: 1000,
      poll: 2000
    }
  }
};

module.exports = config;
<|endoftext|>


<commit_before>"use strict";
/**
 * __template__gist__: https://gist.github.com/tomchentw/368a93bb748ad9d576f1#file-webpack-config-js
 */
var Path = require("path");
var webpack = require("webpack");

var ExtractTextPlugin = require("extract-text-webpack-plugin");
var IsomorphicReactPluginFactory = require("isomorphic-react-plugin-factory");

var publicDirPath = Path.resolve(__dirname, "./public");

var IS_PRODUCTION = "production" === process.env.NODE_ENV;
var IS_DEVELOPMENT = !IS_PRODUCTION;
var BABEL_LOADER = "babel-loader?stage=1";

var HOST = "127.0.0.1";
var PORT = "8001";

var isomorphicReactPlugin = new IsomorphicReactPluginFactory({
  serverComponentPath: "tmp/server.js",
  serverMarkupPath: "tmp/html.js",
  htmlOutputFilename: "index.html",
});

var clientConfig = {
  entry: {
    "assets/client": "./src/client.js",
  },
  output: {
    path: publicDirPath,
    filename: "[name].js",
  },
  module: {
    loaders: [
      {
        test: /\.js(x?)$/,
        exclude: /node_modules/,
        loaders: [BABEL_LOADER],
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader", {
          publicPath: "",
        }),
      },
      {
        test: /\.(otf|eot|svg|ttf|woff|woff2)(\?.+)?$/,
        loaders: [
          "url-loader?limit=8192",
        ],
      }
    ],
  },
  plugins: [
    isomorphicReactPlugin.clientPlugin,
    new ExtractTextPlugin("[name].css", {
      disable: IS_DEVELOPMENT,
    }),
    new webpack.ProvidePlugin({
      "Promise": "bluebird",
      "fetch": "isomorphic-fetch",
    }),
  ],
};

if (IS_DEVELOPMENT) {
  // http://webpack.github.io/docs/hot-module-replacement-with-webpack.html#tutorial
  Object.keys(clientConfig.entry).forEach(function (key) {
    clientConfig.entry[key] = this.concat(clientConfig.entry[key]);
  }, [
    require.resolve("webpack-dev-server/client/") + "?http://" + HOST + ":" + PORT,
    "webpack/hot/dev-server"
  ]);

  clientConfig.module.loaders[0].loaders.unshift("react-hot-loader");

  clientConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin()
  )
} else {
  clientConfig.entry = Object.keys(clientConfig.entry).reduce(function (acc, key) {
    acc[key.replace(/^assets\//, "")] = clientConfig.entry[key];
    return acc;
  }, {});

  clientConfig.output.publicPath = "assets/[hash]/";
  clientConfig.output.path = Path.resolve(publicDirPath, "./" + clientConfig.output.publicPath);

  clientConfig.plugins.push(
    new webpack.optimize.DedupePlugin()
  );
}

var serverConfig = {
  entry: {
    "tmp/server": "./src/server.js",
    "tmp/html": "./src/html.js",
  },
  output: {
    path: publicDirPath,
    filename: "[name].js",
    library: true,
    libraryTarget: "commonjs2",
  },
  target: "node",
  externals: [
    "atob",
    "btoa",
    /* use the same library as node runtime */
    "bluebird",
    "debug",
    "fixed-data-table",
    "isomorphic-fetch",
    "material-ui",
    "react",
    "react/addons",
    "react-tap-event-plugin",
    "rx",
    "rx-react",
  ],
  module: {
    loaders: [
      {
        test: /\.js(x?)$/,
        exclude: /node_modules/,
        loader: BABEL_LOADER,
      },
      {
        test: /\.css$/,
        loaders: [
          "null-loader",
        ],
      },
    ],
  },
  plugins: [
    isomorphicReactPlugin.serverPlugin,
    new webpack.ProvidePlugin({
      "atob": "atob",
      "btoa": "btoa",
      "Promise": "bluebird",
      "fetch": "isomorphic-fetch",
    }),
  ],
};

var webpackConfigsArray = [
  clientConfig,
  serverConfig,
];

webpackConfigsArray.devServer = {
  hot: IS_DEVELOPMENT,
  host: HOST,
  port: PORT,
  contentBase: publicDirPath,
};

module.exports = webpackConfigsArray;
<commit_msg>feat(webpack.config.js): add parseConfig to webpackConfigsArray<commit_after>"use strict";
/**
 * __template__gist__: https://gist.github.com/tomchentw/368a93bb748ad9d576f1#file-webpack-config-js
 */
var Path = require("path");
var webpack = require("webpack");

var ExtractTextPlugin = require("extract-text-webpack-plugin");
var IsomorphicReactPluginFactory = require("isomorphic-react-plugin-factory");

var publicDirPath = Path.resolve(__dirname, "./public");

var IS_PRODUCTION = "production" === process.env.NODE_ENV;
var IS_DEVELOPMENT = !IS_PRODUCTION;
var BABEL_LOADER = "babel-loader?stage=1";

var HOST = "127.0.0.1";
var PORT = "8001";

var isomorphicReactPlugin = new IsomorphicReactPluginFactory({
  serverComponentPath: "tmp/server.js",
  serverMarkupPath: "tmp/html.js",
  htmlOutputFilename: "index.html",
});

var clientConfig = {
  entry: {
    "assets/client": "./src/client.js",
  },
  output: {
    path: publicDirPath,
    filename: "[name].js",
  },
  module: {
    loaders: [
      {
        test: /\.js(x?)$/,
        exclude: /node_modules/,
        loaders: [BABEL_LOADER],
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader", {
          publicPath: "",
        }),
      },
      {
        test: /\.(otf|eot|svg|ttf|woff|woff2)(\?.+)?$/,
        loaders: [
          "url-loader?limit=8192",
        ],
      }
    ],
  },
  plugins: [
    isomorphicReactPlugin.clientPlugin,
    new ExtractTextPlugin("[name].css", {
      disable: IS_DEVELOPMENT,
    }),
    new webpack.ProvidePlugin({
      "Promise": "bluebird",
      "fetch": "isomorphic-fetch",
    }),
  ],
};

if (IS_DEVELOPMENT) {
  // http://webpack.github.io/docs/hot-module-replacement-with-webpack.html#tutorial
  Object.keys(clientConfig.entry).forEach(function (key) {
    clientConfig.entry[key] = this.concat(clientConfig.entry[key]);
  }, [
    require.resolve("webpack-dev-server/client/") + "?http://" + HOST + ":" + PORT,
    "webpack/hot/dev-server"
  ]);

  clientConfig.module.loaders[0].loaders.unshift("react-hot-loader");

  clientConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin()
  )
} else {
  clientConfig.entry = Object.keys(clientConfig.entry).reduce(function (acc, key) {
    acc[key.replace(/^assets\//, "")] = clientConfig.entry[key];
    return acc;
  }, {});

  clientConfig.output.publicPath = "assets/[hash]/";
  clientConfig.output.path = Path.resolve(publicDirPath, "./" + clientConfig.output.publicPath);

  clientConfig.plugins.push(
    new webpack.optimize.DedupePlugin()
  );
}

var serverConfig = {
  entry: {
    "tmp/server": "./src/server.js",
    "tmp/html": "./src/html.js",
  },
  output: {
    path: publicDirPath,
    filename: "[name].js",
    library: true,
    libraryTarget: "commonjs2",
  },
  target: "node",
  externals: [
    "atob",
    "btoa",
    /* use the same library as node runtime */
    "bluebird",
    "debug",
    "fixed-data-table",
    "isomorphic-fetch",
    "material-ui",
    "react",
    "react/addons",
    "react-tap-event-plugin",
    "rx",
    "rx-react",
  ],
  module: {
    loaders: [
      {
        test: /\.js(x?)$/,
        exclude: /node_modules/,
        loader: BABEL_LOADER,
      },
      {
        test: /\.css$/,
        loaders: [
          "null-loader",
        ],
      },
    ],
  },
  plugins: [
    isomorphicReactPlugin.serverPlugin,
    new webpack.ProvidePlugin({
      "atob": "atob",
      "btoa": "btoa",
      "Promise": "bluebird",
      "fetch": "isomorphic-fetch",
    }),
  ],
};

var parseConfig = {
  entry: {
    "main": "./src/parse.js",
  },
  output: {
    path: Path.resolve(__dirname, "./cloud"),
    filename: "[name].js",
  },
  target: "node",
  module: {
    loaders: [
      {
        test: /\.js(x?)$/,
        exclude: /node_modules/,
        loader: BABEL_LOADER,
      },
    ],
  },
  plugins: [
  ],
};

var webpackConfigsArray = [
  clientConfig,
  serverConfig,
  parseConfig,
];

webpackConfigsArray.devServer = {
  hot: IS_DEVELOPMENT,
  host: HOST,
  port: PORT,
  contentBase: publicDirPath,
};

module.exports = webpackConfigsArray;
<|endoftext|>


<commit_before>var path = require("path");
var webpack = require("webpack");
module.exports = {
  context: path.join(__dirname, "src"),
  entry: {
    "extension/devtools/panel/bundle": "./panel.js",
    "/docs/bundle": "./index.js"
  },
  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, ".")
  },
  plugins: [new webpack.EnvironmentPlugin(["NODE_ENV"])]
};
<commit_msg>udpate webpack to handle a separate .src file for extension<commit_after>var path = require("path");
var webpack = require("webpack");
module.exports = {
  context: path.join(__dirname),
  entry: {
    "extension/devtools/panel/bundle": "./extension/src/panel.js",
    "/docs/bundle": "./index.js"
  },
  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, ".")
  },
  plugins: [new webpack.EnvironmentPlugin(["NODE_ENV"])]
};
<|endoftext|>


<commit_before>"use strict";

const path = require("path");
const webpack = require("webpack");
const autoprefixer = require("autoprefixer");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextWebpackPlugin = require("extract-text-webpack-plugin");
const WebpackSHAHash = require('webpack-sha-hash');

// Metadata
var ENV = process.env.ENV = process.env.NODE_ENV = "development";

const metadata = {
    title: "AngularJS Webpack Starter",
    baseUrl: "/",
    host: "localhost",
    port: 3000,
    ENV: ENV
};

/*
 * Config
 */
module.exports = {
    // static data for index.html
    metadata: metadata,
    // for faster builds use "eval"
    devtool: "source-map",
    debug: true,

    // our angular app
    entry: {
        "vendor": "./src/vendor.ts",
        "main": "./src/main.ts"
    },

    // Config for our build files
    // Adding hashes to files for cache busting
    output: {
        path: root("dist"),
        filename: "[name].[hash].bundle.js",
        //sourceMapFilename: "[name].[hash].map",
        chunkFilename: "[id].[hash].chunk.js"
    },

    resolve: {
        // ensure loader extensions match
        extensions: ["", ".ts", ".js", ".json", ".css", ".scss", ".html"]
    },

    module: {
        preLoaders: [
            {test: /\.ts$/, loader: "tslint", exclude: [/node_modules/]}],
        loaders: [
            // Support for *.json files.
            {test: /\.json$/, loader: "json"},

            // Support for CSS as raw text
            {test: /\.css$/, loader: "raw"},

            // Use style in development for hot-loading
            {test: /\.scss$/, loader: ExtractTextWebpackPlugin.extract("style", "css?sourceMap!postcss!sass")},

            // Support for .html as raw text
            {test: /\.html$/, loader: "raw", exclude: [ root("src/index.html") ]},

            // Support for .ts files.
            {
                test: /\.ts$/,
                loader: "ts",
                exclude: [
                    /\.e2e\.ts$/,
                    /\.spec\.ts$/,
                ]
            }

            // if you add a loader include the resolve file extension above
        ]
    },

    plugins: [
        // content hashes
        new WebpackSHAHash(),

        // optimization
        new webpack.optimize.OccurenceOrderPlugin(true),
        new webpack.optimize.CommonsChunkPlugin({
            name: "vendor",
            filename: "vendor.[hash].bundle.js",
            minChunks: Infinity
        }),

        // static assets
        new CopyWebpackPlugin([{
            from: "src/assets",
            to: "assets"
        }]),

        // Extract css files
        // Reference: https://github.com/webpack/extract-text-webpack-plugin
        new ExtractTextWebpackPlugin("[name].[hash].css", {
            disable: false}
        ),

        // generating html
        // Reference: https://github.com/ampedandwired/html-webpack-plugin
        new HtmlWebpackPlugin({
            template: "src/index.html"
        }),

        // replace
        new webpack.DefinePlugin({
            "process.env": {
                "ENV": JSON.stringify(metadata.ENV),
                "NODE_ENV": JSON.stringify(metadata.ENV)
            }
        })
    ],

    /**
     * PostCSS
     * Reference: https://github.com/postcss/autoprefixer
     * Add vendor prefixes to css
     */
    postcss: [
        autoprefixer({
            browsers: ["last 2 versions"]
        })
    ],

    // Other module loader config
    tslint: {
        emitErrors: false,
        failOnHint: false
    },
    // our Webpack Development Server config
    devServer: {
        port: metadata.port,
        host: metadata.host,
        historyApiFallback: true,
        watchOptions: {aggregateTimeout: 300, poll: 1000}
    },
    // we need this due to problems with es6-shim
    node: {
        global: "window",
        progress: false,
        crypto: "empty",
        module: false,
        clearImmediate: false,
        setImmediate: false
    }
};

// Helper functions

function root(args) {
    args = Array.prototype.slice.call(arguments, 0);
    return path.join.apply(path, [__dirname].concat(args));
}

function rootNode(args) {
    args = Array.prototype.slice.call(arguments, 0);
    return root.apply(path, ["node_modules"].concat(args));
}
<commit_msg>Improved SASS support<commit_after>"use strict";

const path = require("path");
const webpack = require("webpack");
const autoprefixer = require("autoprefixer");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const WebpackSHAHash = require('webpack-sha-hash');

// Metadata
var ENV = process.env.ENV = process.env.NODE_ENV = "development";

const metadata = {
    title: "AngularJS Webpack Starter",
    baseUrl: "/",
    host: "localhost",
    port: 3000,
    ENV: ENV
};

/*
 * Config
 */
module.exports = {
    // static data for index.html
    metadata: metadata,
    // for faster builds use "eval"
    devtool: "source-map",
    debug: true,

    // our angular app
    entry: {
        "vendor": "./src/vendor.ts",
        "main": "./src/main.ts"
    },

    // Config for our build files
    // Adding hashes to files for cache busting
    output: {
        path: root("dist"),
        filename: "[name].[hash].bundle.js",
        //sourceMapFilename: "[name].[hash].map",
        chunkFilename: "[id].[hash].chunk.js"
    },

    resolve: {
        // ensure loader extensions match
        extensions: ["", ".ts", ".js", ".json", ".css", ".scss", ".html"]
    },

    module: {
        preLoaders: [{
                test: /\.ts$/,
                loader: "tslint",
                exclude: [
                    /node_modules/
                ]
        }],
        loaders: [
            // Support for *.json files.
            {
                test: /\.json$/,
                loader: "json"
            },

            // Support for CSS as raw text
            {
                test: /\.css$/,
                loader: "raw"
            },

            // Use style in development for hot-loading
            // Reference: http://ihaveabackup.net/2015/08/17/sass-with-sourcemaps-webpack-and-live-reload/
            {
                test: /\.scss$/,
                loaders: [ 'style', 'css?sourceMap', 'postcss?sourceMap', 'sass?sourceMap' ]
            },

            // Support for .html as raw text
            {
                test: /\.html$/,
                loader: "raw",
                exclude: [
                    root("src/index.html")
                ]
            },

            // Support for .ts files.
            {
                test: /\.ts$/,
                loader: "ts",
                exclude: [
                    /\.e2e\.ts$/,
                    /\.spec\.ts$/,
                ]
            }

            // if you add a loader include the resolve file extension above
        ]
    },

    plugins: [
        // content hashes
        new WebpackSHAHash(),

        // optimization
        new webpack.optimize.OccurenceOrderPlugin(true),
        new webpack.optimize.CommonsChunkPlugin({
            name: "vendor",
            filename: "vendor.[hash].bundle.js",
            minChunks: Infinity
        }),

        // static assets
        new CopyWebpackPlugin([{
            from: "src/assets",
            to: "assets"
        }]),

        // generating html
        // Reference: https://github.com/ampedandwired/html-webpack-plugin
        new HtmlWebpackPlugin({
            template: "src/index.html"
        }),

        // replace
        new webpack.DefinePlugin({
            "process.env": {
                "ENV": JSON.stringify(metadata.ENV),
                "NODE_ENV": JSON.stringify(metadata.ENV)
            }
        })
    ],

    /**
     * PostCSS
     * Reference: https://github.com/postcss/autoprefixer
     * Add vendor prefixes to css
     */
    postcss: [
        autoprefixer({
            browsers: ["last 2 versions"]
        })
    ],

    // Other module loader config
    tslint: {
        emitErrors: false,
        failOnHint: false
    },
    // our Webpack Development Server config
    devServer: {
        port: metadata.port,
        host: metadata.host,
        historyApiFallback: true,
        watchOptions: {aggregateTimeout: 300, poll: 1000}
    },
    // we need this due to problems with es6-shim
    node: {
        global: "window",
        progress: false,
        crypto: "empty",
        module: false,
        clearImmediate: false,
        setImmediate: false
    }
};

// Helper functions

function root(args) {
    args = Array.prototype.slice.call(arguments, 0);
    return path.join.apply(path, [__dirname].concat(args));
}

function rootNode(args) {
    args = Array.prototype.slice.call(arguments, 0);
    return root.apply(path, ["node_modules"].concat(args));
}
<|endoftext|>


<commit_before>const date = require('../date-and-time');
const rand = (min, max) => ((Math.random() * (max - min) + min) | 0);
const M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const A = ['a.m.', 'p.m.'];
const dateString = [];
const formatString = 'MMM. D YYYY h:m:s A';
const cnt = 6553500;

console.log('Creating a list of random date string...');

for (let i = 0; i < cnt; i++) {
    const month = M[rand(0, 12)];
    const day = '' + rand(1, 29);
    const year = '' + rand(2000, 2020);
    const hour = '' + rand(0, 12);
    const minute = '' + rand(0, 60);
    const sec = '' + rand(0, 60);
    const ampm = A[rand(0, 2)];
    dateString.push(`${month}. ${day} ${year} ${hour}:${minute}:${sec} ${ampm}`);
}

console.log('Starting the benchmark.\n');
let start = Date.now();

for (let i = 0; i < cnt; i++) {
    date.parse(dateString[i], formatString);
}

const bench1 = Date.now() - start;
console.log(`parse() only: ${bench1}ms`);

start = Date.now();
const pattern = date.compile(formatString);

for (let i = 0; i < cnt; i++) {
    date.parse(dateString[i], pattern);
}

const bench2 = Date.now() - start;
console.log(`compile() + parse(): ${bench2}ms (${Math.round(bench2 / bench1 * 100)}%)`);
<commit_msg>Added test for the ormat()<commit_after>const date = require('../date-and-time');
const rand = (min, max) => ((Math.random() * (max - min) + min) | 0);
const M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const A = ['a.m.', 'p.m.'];
const dates = [];
const dateString = [];
const formatString = 'MMM. D YYYY h:m:s A';
const cnt = 3000000;

console.log('Creating a list of random date string...');

for (let i = 0; i < cnt; i++) {
    const month = rand(0, 12);
    const day = '' + rand(1, 29);
    const year = '' + rand(2000, 2020);
    const hour = '' + rand(0, 12);
    const minute = '' + rand(0, 60);
    const sec = '' + rand(0, 60);
    const ampm = rand(0, 2);
    dates.push(new Date(year, month, day, hour + 12 * ampm, minute, sec));
    dateString.push(`${M[month]}. ${day} ${year} ${hour}:${minute}:${sec} ${A[ampm]}`);
}

console.log('Starting the benchmark.\n');

let start = Date.now();

for (let i = 0; i < cnt; i++) {
    date.format(dates[i], formatString);
}

const bench1 = Date.now() - start;
console.log(`format(): ${bench1}ms`);

start = Date.now();
const pattern1 = date.compile(formatString);

for (let i = 0; i < cnt; i++) {
    date.format(dates[i], pattern1);
}

const bench2 = Date.now() - start;
console.log(`format() with compile(): ${bench2}ms (${Math.round(bench2 / bench1 * 100)}%)`);

start = Date.now();

for (let i = 0; i < cnt; i++) {
    date.parse(dateString[i], formatString);
}

const bench3 = Date.now() - start;
console.log(`parse(): ${bench3}ms`);

start = Date.now();
const pattern2 = date.compile(formatString);

for (let i = 0; i < cnt; i++) {
    date.parse(dateString[i], pattern2);
}

const bench4 = Date.now() - start;
console.log(`parse() with compile(): ${bench2}ms (${Math.round(bench4 / bench3 * 100)}%)`);
<|endoftext|>


<commit_before>var rootpath = require('path').resolve(__dirname)

var webpack = require('webpack')
var autoprefixer = require('autoprefixer')
var HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './app/client/index.tsx',
  output: { path: './build/', filename: 'bundle.js', publicPath: '/' },
  module: {
    loaders: [
      {
        test: /\.(ts|tsx?)$/,
        loader: 'ts-loader',
        exclude: /node_modules/
      },
      {
        test: /\.less$/,
        loader: 'style-loader!css-loader!postcss-loader!less-loader'
      },
    ]
  },
  resolve: {
    root: [rootpath, `${rootpath}/app`, `${rootpath}/client`],
    extensions: ['', '.js', '.ts', '.tsx']
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': "'production'"
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    new HtmlWebpackPlugin({
      template: `${rootpath}/app/client/index.html`,
      filename: `./index.html`
    })
  ],
  postcss: () => [autoprefixer],
  devtool: 'source-map',
  devServer: { historyApiFallback: true, host: '0.0.0.0', port: 8080 }
}
<commit_msg>webpack no minification in dev<commit_after>var webpack = require('webpack')
var autoprefixer = require('autoprefixer')
var HtmlWebpackPlugin = require('html-webpack-plugin')

var rootpath = require('path').resolve(__dirname)
var isDev = process.env.npm_lifecycle_event === 'dev'
var isProd = !isDev

module.exports = {
  entry: './app/client/index.tsx',
  output: { path: './build/', filename: 'bundle.js', publicPath: '/' },
  module: {
    loaders: [
      {
        test: /\.(ts|tsx?)$/,
        loader: 'ts-loader',
        exclude: /node_modules/
      },
      {
        test: /\.less$/,
        loader: 'style-loader!css-loader!postcss-loader!less-loader'
      },
    ]
  },
  resolve: {
    root: [rootpath, `${rootpath}/app`, `${rootpath}/client`],
    extensions: ['', '.js', '.ts', '.tsx']
  },
  plugins: [
    isProd ? new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': "'production'" } }) : function() {},
    isProd ? new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) : function() {},
    new HtmlWebpackPlugin({
      template: `${rootpath}/app/client/index.html`,
      filename: `./index.html`
    })
  ],
  postcss: () => [autoprefixer],
  devtool: 'source-map',
  devServer: { historyApiFallback: true, host: '0.0.0.0', port: 8080 }
}
<|endoftext|>


<commit_before>const shadowsocks_presets = [
  // [stream ciphers]
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-cfb"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "rc4-md5"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "camellia-256-cfb"}}
  ],
  // [aead ciphers]
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "chacha20-poly1305"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "chacha20-ietf-poly1305"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "xchacha20-ietf-poly1305"}}
  ]
];
const shadowsocks_obfs_presets = [
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "obfs-random-padding"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "obfs-random-padding"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ]
];

const shadowsocksr_presets = [
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-aes128-md5"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-aes128-sha1"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-chain-a"},
    {"name": "ss-stream-cipher", "params": {"method": "none"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-chain-b"},
    {"name": "ss-stream-cipher", "params": {"method": "none"}}
  ]
];
const shadowsocksr_obfs_presets = [
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-aes128-sha1"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-chain-a"},
    {"name": "ss-stream-cipher", "params": {"method": "none"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ]
];

const v2ray_presets = [
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "none"}}],
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "aes-128-gcm"}}],
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "chacha20-poly1305"}}]
];
const v2ray_obfs_presets = [
  [
    {"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "aes-128-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ]
];

const blinksocks_presets = [
  [
    {"name": "base-auth"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}}
  ]
];
const blinksocks_obfs_presets = [
  [
    {"name": "base-auth"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "base-auth"},
    {"name": "obfs-random-padding"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "base-auth"},
    {"name": "obfs-random-padding"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ]
];

module.exports = [
  ...shadowsocks_presets,
  ...shadowsocks_obfs_presets,
  ...shadowsocksr_presets,
  ...shadowsocksr_obfs_presets,
  ...v2ray_presets,
  ...v2ray_obfs_presets,
  ...blinksocks_presets,
  ...blinksocks_obfs_presets
];
<commit_msg>benchmark: add test case for chacha20-ietf<commit_after>const shadowsocks_presets = [
  // [stream ciphers]
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-cfb"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "rc4-md5"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "camellia-256-cfb"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "chacha20-ietf"}}
  ],
  // [aead ciphers]
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "chacha20-poly1305"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "chacha20-ietf-poly1305"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "xchacha20-ietf-poly1305"}}
  ]
];
const shadowsocks_obfs_presets = [
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "obfs-random-padding"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "obfs-random-padding"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ]
];

const shadowsocksr_presets = [
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-aes128-md5"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-aes128-sha1"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-chain-a"},
    {"name": "ss-stream-cipher", "params": {"method": "none"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-chain-b"},
    {"name": "ss-stream-cipher", "params": {"method": "none"}}
  ]
];
const shadowsocksr_obfs_presets = [
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-aes128-sha1"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ssr-auth-chain-a"},
    {"name": "ss-stream-cipher", "params": {"method": "none"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ]
];

const v2ray_presets = [
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "none"}}],
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "aes-128-gcm"}}],
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "chacha20-poly1305"}}]
];
const v2ray_obfs_presets = [
  [
    {"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "aes-128-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ]
];

const blinksocks_presets = [
  [
    {"name": "base-auth"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}}
  ]
];
const blinksocks_obfs_presets = [
  [
    {"name": "base-auth"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "base-auth"},
    {"name": "obfs-random-padding"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "base-auth"},
    {"name": "obfs-random-padding"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ]
];

module.exports = [
  ...shadowsocks_presets,
  ...shadowsocks_obfs_presets,
  ...shadowsocksr_presets,
  ...shadowsocksr_obfs_presets,
  ...v2ray_presets,
  ...v2ray_obfs_presets,
  ...blinksocks_presets,
  ...blinksocks_obfs_presets
];
<|endoftext|>


<commit_before>'use strict';
var path = require('path');

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var Clean = require('clean-webpack-plugin');
var merge = require('webpack-merge');

var pkg = require('./package.json');

var TARGET = process.env.npm_lifecycle_event;
var ROOT_PATH = path.resolve(__dirname);
var DEMO_DIR = 'demo';
var config = {
  paths: {
    dist: path.join(ROOT_PATH, 'dist'),
    src: path.join(ROOT_PATH, 'src'),
    demo: path.join(ROOT_PATH, DEMO_DIR),
    demoIndex: path.join(ROOT_PATH, DEMO_DIR, '/index'),
  },
  filename: 'boilerplate',
  library: 'Boilerplate',
};

var mergeDemo = merge.bind(null, {
  resolve: {
    extensions: ['', '.js', '.jsx', '.md', '.css', '.png', '.jpg'],
  },
  module: {
    loaders: [
      {
        test: /\.css$/,
        loaders: ['style', 'css'],
      },
      {
        test: /\.md$/,
        loaders: ['html', 'highlight', 'markdown'],
      },
      {
        test: /\.png$/,
        loader: 'url?limit=100000&mimetype=image/png',
        include: config.paths.demo,
      },
      {
        test: /\.jpg$/,
        loader: 'file',
        include: config.paths.demo,
      },
      {
        test: /\.json$/,
        loader: 'json',
      },
    ]
  }
});

if (TARGET === 'start') {
  var IP = '0.0.0.0';
  var PORT = 3000;
  module.exports = mergeDemo({
    ip: IP,
    port: PORT,
    devtool: 'eval-source-map',
    entry: [
      'webpack-dev-server/client?http://' + IP + ':' + PORT,
      'webpack/hot/only-dev-server',
      config.paths.demoIndex,
    ],
    output: {
      path: __dirname,
      filename: 'bundle.js'
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('development'),
        }
      }),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin(),
      new HtmlWebpackPlugin(),
    ],
    module: {
      preLoaders: [
        {
          test: /\.jsx?$/,
          loaders: ['eslint'],
          include: [config.paths.demo, config.paths.src],
        }
      ],
      loaders: [
        {
          test: /\.jsx?$/,
          loaders: ['react-hot', 'babel'],
          include: [config.paths.demo, config.paths.src],
        },
      ]
    }
  });
}

if (TARGET === 'gh-pages' || TARGET === 'deploy-gh-pages') {
  module.exports = mergeDemo({
    entry: {
      app: config.paths.demoIndex,
      // tweak this to include your externs unless you load them some other way
      vendors: ['react/addons'],
    },
    output: {
      path: './gh-pages',
      filename: 'bundle.[chunkhash].js',
    },
    plugins: [
      new Clean(['gh-pages']),
      new webpack.DefinePlugin({
        'process.env': {
          // This has effect on the react lib size
          'NODE_ENV': JSON.stringify('production'),
        }
      }),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        },
      }),
      new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.[chunkhash].js'),
      new HtmlWebpackPlugin({
        title: pkg.name + ' - ' + pkg.description
      }),
    ],
    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          loaders: ['babel'],
          include: [config.paths.demo, config.paths.src],
        }
      ]
    }
  });
}

var mergeDist = merge.bind(null, {
  devtool: 'source-map',
  output: {
    path: config.paths.dist,
    libraryTarget: 'umd',
    library: config.library,
  },
  entry: config.paths.src,
  externals: {
    //// if you are not testing, just react will do
    //react: 'react',
    'react/addons': 'react/addons'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loaders: ['babel'],
        include: config.paths.src,
      }
    ]
  }
});

if (TARGET === 'dist') {
  module.exports = mergeDist({
    output: {
      filename: config.filename + '.js',
    },
  });
}

if (TARGET === 'dist-min') {
  module.exports = mergeDist({
    output: {
      filename: config.filename + '.min.js',
    },
    plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
    }),
    ],
  });
}
<commit_msg>Add better default externals for React<commit_after>'use strict';
var path = require('path');

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var Clean = require('clean-webpack-plugin');
var merge = require('webpack-merge');

var pkg = require('./package.json');

var TARGET = process.env.npm_lifecycle_event;
var ROOT_PATH = path.resolve(__dirname);
var DEMO_DIR = 'demo';
var config = {
  paths: {
    dist: path.join(ROOT_PATH, 'dist'),
    src: path.join(ROOT_PATH, 'src'),
    demo: path.join(ROOT_PATH, DEMO_DIR),
    demoIndex: path.join(ROOT_PATH, DEMO_DIR, '/index'),
  },
  filename: 'boilerplate',
  library: 'Boilerplate',
};

var mergeDemo = merge.bind(null, {
  resolve: {
    extensions: ['', '.js', '.jsx', '.md', '.css', '.png', '.jpg'],
  },
  module: {
    loaders: [
      {
        test: /\.css$/,
        loaders: ['style', 'css'],
      },
      {
        test: /\.md$/,
        loaders: ['html', 'highlight', 'markdown'],
      },
      {
        test: /\.png$/,
        loader: 'url?limit=100000&mimetype=image/png',
        include: config.paths.demo,
      },
      {
        test: /\.jpg$/,
        loader: 'file',
        include: config.paths.demo,
      },
      {
        test: /\.json$/,
        loader: 'json',
      },
    ]
  }
});

if (TARGET === 'start') {
  var IP = '0.0.0.0';
  var PORT = 3000;
  module.exports = mergeDemo({
    ip: IP,
    port: PORT,
    devtool: 'eval-source-map',
    entry: [
      'webpack-dev-server/client?http://' + IP + ':' + PORT,
      'webpack/hot/only-dev-server',
      config.paths.demoIndex,
    ],
    output: {
      path: __dirname,
      filename: 'bundle.js'
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('development'),
        }
      }),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin(),
      new HtmlWebpackPlugin(),
    ],
    module: {
      preLoaders: [
        {
          test: /\.jsx?$/,
          loaders: ['eslint'],
          include: [config.paths.demo, config.paths.src],
        }
      ],
      loaders: [
        {
          test: /\.jsx?$/,
          loaders: ['react-hot', 'babel'],
          include: [config.paths.demo, config.paths.src],
        },
      ]
    }
  });
}

if (TARGET === 'gh-pages' || TARGET === 'deploy-gh-pages') {
  module.exports = mergeDemo({
    entry: {
      app: config.paths.demoIndex,
      // tweak this to include your externs unless you load them some other way
      vendors: ['react/addons'],
    },
    output: {
      path: './gh-pages',
      filename: 'bundle.[chunkhash].js',
    },
    plugins: [
      new Clean(['gh-pages']),
      new webpack.DefinePlugin({
        'process.env': {
          // This has effect on the react lib size
          'NODE_ENV': JSON.stringify('production'),
        }
      }),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        },
      }),
      new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.[chunkhash].js'),
      new HtmlWebpackPlugin({
        title: pkg.name + ' - ' + pkg.description
      }),
    ],
    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          loaders: ['babel'],
          include: [config.paths.demo, config.paths.src],
        }
      ]
    }
  });
}

var mergeDist = merge.bind(null, {
  devtool: 'source-map',
  output: {
    path: config.paths.dist,
    libraryTarget: 'umd',
    library: config.library,
  },
  entry: config.paths.src,
  externals: {
    // if you are not testing,
    // just 'react' instead of 'react/addons'
    // will be enough
    'react/addons': {
        commonjs: 'react/addons',
        commonjs2: 'react/addons',
        amd: 'React',
        root: 'React'
    }
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loaders: ['babel'],
        include: config.paths.src,
      }
    ]
  }
});

if (TARGET === 'dist') {
  module.exports = mergeDist({
    output: {
      filename: config.filename + '.js',
    },
  });
}

if (TARGET === 'dist-min') {
  module.exports = mergeDist({
    output: {
      filename: config.filename + '.min.js',
    },
    plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
    }),
    ],
  });
}
<|endoftext|>