<commit_before>/*global require: false, module: false, __dirname: false */
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

var reactToolboxVariables = require('./reactToolboxVariables');

var postcssPlugins = [
	require('postcss-for'),
	require('postcss-cssnext')({
		features: {
			customProperties: {
				variables: reactToolboxVariables
			}
		}
	}),
	require('postcss-modules-values')
];

var htmlPlugin = process.argv.indexOf('--disable-html-plugin') === -1 ?
	[new HtmlWebpackPlugin({
		title: "UCSC Xena",
		filename: "index.html",
		inject: false,
		//template: "!!blueimp-tmpl-loader!page.template"
		template: "page.template"
	})] : [];

module.exports = {
	mode: 'development',
	entry: {heatmap: './js/main', docs: './js/docs', bookmarks: './js/admin/bookmarks.js'},
	output: {
		path: __dirname + "/build",
		publicPath: "../",
		filename: "[name].js"
	},
	devServer: {
		host: "localhost",
		publicPath: '/',
		disableHostCheck: true,
		historyApiFallback: true,
		headers: {
			"Content-Security-Policy-Report-Only": "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval blob:'; style-src 'self' 'unsafe-inline'; connect-src *; img-src * data:; frame-src 'self' ucscxena: https://www.youtube.com https://xenageneset.berkeleybop.io/xena/"
		},
		proxy: {
			'/api/**': {
				changeOrigin: true,
				target: 'http://dev.xenabrowser.net/api',
				// For local django dev, use this instead & remove changeOrigin.
//				target: 'http://localhost:8000/',
				pathRewrite: {'^/api': ''}
			}
		}
	},
	module: {
		rules: [
			{ test: /loadXenaQueries.js$/, loader: "val-loader" },
			{ test: /\.xq$/, loader: "raw-loader" },
			//// bunch of special loading required for pdfkit
			{
				test: /png-js|fontkit[/\\]index.js$|unicode-properties[/\\]index.js$/,
				use: [
					{ loader: 'transform-loader', options: { brfs: true } },
					{ loader: 'babel-loader' }
				]
			},
			{
				test: /pdfkit.js/,
				use: [
					{ loader: 'transform-loader', options: { brfs: true } },
					{ loader: 'babel-loader' }
				]
			},
			{ test: path => path.match(/@hms-dbmi[/\\]viv[/\\]dist[/\\]viv.es.js/),
				loader: "babel-loader"},
			{ test: /dfa[/\\]index.js/, loader: "babel-loader" },
			{ test: /svg-to-pdfkit[/\\]source.js/, loader: "babel-loader" },
			{ test: /unicode-trie[/\\]index.js/, loader: "babel-loader" },
			{ test: /unicode-trie[/\\]swap.js/, loader: "babel-loader" },
			{ test: /linebreak[/\\]src[/\\]pairs.js/, loader: "babel-loader" },
			{
				test: /linebreak[/\\]src[/\\]linebreaker.js/,
				use: [
					{ loader: 'transform-loader', options: { brfs: true } },
					{ loader: 'babel-loader' }
				]
			},
			{ test: /unicode-properties[/\\]unicode-properties.browser.cjs.js/, loader: "babel-loader" },
			{ test: /src[/\\]assets/, loader: "arraybuffer-loader" },
			{ test: /\.afm$/, loader: "raw-loader" },
			{
				test: /\.jsx?$/,
				include: [
					path.join(__dirname, 'js'),
					path.join(__dirname, 'test'),
					path.join(__dirname, 'doc')
				],
				loader: ['babel-loader']
			},
			{
				// css modules
				test: path => path.match(/\.css$/) && (path.indexOf('toolbox') !== -1 || path.match(/\.module\.css$/)),
				// must be two-element array. See webpack.prod.js
				use: [
					{ loader: 'style-loader'},
					{
						loader: 'css-loader',
						options: {
							sourceMap: true,
							modules: {
								localIdentName: '[name]__[local]___[hash:base64:5]'
							},
							importLoaders: 1,
						}
					},
					{
						loader: 'postcss-loader',
						options: {
							sourceMap: true,
							sourceComments: true,
							plugins: () => postcssPlugins
						}
					}
				]
			},
			{
				// 'modules' breaks existing css, so handle them separately
				test: path => path.match(/\.css$/) && !(path.indexOf('toolbox') !== -1 || path.match(/\.module\.css$/)),
				// must be two-element array. See webpack.prod.js
				use: [
					{ loader: 'style-loader' },
					{
						loader: 'css-loader',
						options: {
							importLoaders: 1,
						}
					},
					{
						loader: 'postcss-loader',
						options: {
							sourceMap: true,
							plugins: () => postcssPlugins
						}
					}
				]
			},
			{
				test: /\.(jpe?g|png|gif|svg|eot|woff2?|ttf)$/i,
				loader: 'file-loader'
			}
		]
	},
	plugins: htmlPlugin.concat([]),
	resolve: {
		// pdfkit exports es6 modules, which webpack will prefer by default, but
		// getting them to build correctly is extremely complicated. So, we configure
		// webpack to prefer commonjs modules ('main').
		mainFields: ['browser', 'main', 'module'],
		alias: {
			'redboxOptions': path.join(__dirname, 'redboxOptions.json'),
			'redux-devtools': path.join(__dirname, 'js/redux-devtool-shim'),
			'fs': 'pdfkit/js/virtual-fs.js',
			'txml/txml': 'txml/dist/txml'
		},
		symlinks: false,
		extensions: ['.js', '.jsx', '.json']
	}
};
<commit_msg>Fix webpack csp<commit_after>/*global require: false, module: false, __dirname: false */
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

var reactToolboxVariables = require('./reactToolboxVariables');

var postcssPlugins = [
	require('postcss-for'),
	require('postcss-cssnext')({
		features: {
			customProperties: {
				variables: reactToolboxVariables
			}
		}
	}),
	require('postcss-modules-values')
];

var htmlPlugin = process.argv.indexOf('--disable-html-plugin') === -1 ?
	[new HtmlWebpackPlugin({
		title: "UCSC Xena",
		filename: "index.html",
		inject: false,
		//template: "!!blueimp-tmpl-loader!page.template"
		template: "page.template"
	})] : [];

module.exports = {
	mode: 'development',
	entry: {heatmap: './js/main', docs: './js/docs', bookmarks: './js/admin/bookmarks.js'},
	output: {
		path: __dirname + "/build",
		publicPath: "../",
		filename: "[name].js"
	},
	devServer: {
		host: "localhost",
		publicPath: '/',
		disableHostCheck: true,
		historyApiFallback: true,
		headers: {
			"Content-Security-Policy-Report-Only": "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; style-src 'self' 'unsafe-inline'; connect-src *; img-src * data:; frame-src 'self' ucscxena: https://www.youtube.com https://xenageneset.berkeleybop.io/xena/"
		},
		proxy: {
			'/api/**': {
				changeOrigin: true,
				target: 'http://dev.xenabrowser.net/api',
				// For local django dev, use this instead & remove changeOrigin.
//				target: 'http://localhost:8000/',
				pathRewrite: {'^/api': ''}
			}
		}
	},
	module: {
		rules: [
			{ test: /loadXenaQueries.js$/, loader: "val-loader" },
			{ test: /\.xq$/, loader: "raw-loader" },
			//// bunch of special loading required for pdfkit
			{
				test: /png-js|fontkit[/\\]index.js$|unicode-properties[/\\]index.js$/,
				use: [
					{ loader: 'transform-loader', options: { brfs: true } },
					{ loader: 'babel-loader' }
				]
			},
			{
				test: /pdfkit.js/,
				use: [
					{ loader: 'transform-loader', options: { brfs: true } },
					{ loader: 'babel-loader' }
				]
			},
			{ test: path => path.match(/@hms-dbmi[/\\]viv[/\\]dist[/\\]viv.es.js/),
				loader: "babel-loader"},
			{ test: /dfa[/\\]index.js/, loader: "babel-loader" },
			{ test: /svg-to-pdfkit[/\\]source.js/, loader: "babel-loader" },
			{ test: /unicode-trie[/\\]index.js/, loader: "babel-loader" },
			{ test: /unicode-trie[/\\]swap.js/, loader: "babel-loader" },
			{ test: /linebreak[/\\]src[/\\]pairs.js/, loader: "babel-loader" },
			{
				test: /linebreak[/\\]src[/\\]linebreaker.js/,
				use: [
					{ loader: 'transform-loader', options: { brfs: true } },
					{ loader: 'babel-loader' }
				]
			},
			{ test: /unicode-properties[/\\]unicode-properties.browser.cjs.js/, loader: "babel-loader" },
			{ test: /src[/\\]assets/, loader: "arraybuffer-loader" },
			{ test: /\.afm$/, loader: "raw-loader" },
			{
				test: /\.jsx?$/,
				include: [
					path.join(__dirname, 'js'),
					path.join(__dirname, 'test'),
					path.join(__dirname, 'doc')
				],
				loader: ['babel-loader']
			},
			{
				// css modules
				test: path => path.match(/\.css$/) && (path.indexOf('toolbox') !== -1 || path.match(/\.module\.css$/)),
				// must be two-element array. See webpack.prod.js
				use: [
					{ loader: 'style-loader'},
					{
						loader: 'css-loader',
						options: {
							sourceMap: true,
							modules: {
								localIdentName: '[name]__[local]___[hash:base64:5]'
							},
							importLoaders: 1,
						}
					},
					{
						loader: 'postcss-loader',
						options: {
							sourceMap: true,
							sourceComments: true,
							plugins: () => postcssPlugins
						}
					}
				]
			},
			{
				// 'modules' breaks existing css, so handle them separately
				test: path => path.match(/\.css$/) && !(path.indexOf('toolbox') !== -1 || path.match(/\.module\.css$/)),
				// must be two-element array. See webpack.prod.js
				use: [
					{ loader: 'style-loader' },
					{
						loader: 'css-loader',
						options: {
							importLoaders: 1,
						}
					},
					{
						loader: 'postcss-loader',
						options: {
							sourceMap: true,
							plugins: () => postcssPlugins
						}
					}
				]
			},
			{
				test: /\.(jpe?g|png|gif|svg|eot|woff2?|ttf)$/i,
				loader: 'file-loader'
			}
		]
	},
	plugins: htmlPlugin.concat([]),
	resolve: {
		// pdfkit exports es6 modules, which webpack will prefer by default, but
		// getting them to build correctly is extremely complicated. So, we configure
		// webpack to prefer commonjs modules ('main').
		mainFields: ['browser', 'main', 'module'],
		alias: {
			'redboxOptions': path.join(__dirname, 'redboxOptions.json'),
			'redux-devtools': path.join(__dirname, 'js/redux-devtool-shim'),
			'fs': 'pdfkit/js/virtual-fs.js',
			'txml/txml': 'txml/dist/txml'
		},
		symlinks: false,
		extensions: ['.js', '.jsx', '.json']
	}
};
<|endoftext|>


<commit_before>const config = require('config')
const WebpackCdnPlugin = require('webpack-cdn-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const packageJson = require('./package.json')

module.exports = (_env, argv) => {
	const dev = argv.mode === 'development'
	const reactMode = dev ? 'development' : 'production.min'
	const min = dev ? '' : '.min'

	return {
		entry: {
			app: './web'
		},
		output: {
			publicPath: '/',
			filename: '[name].[chunkhash:8].js'
		},
		module: {
			rules: [
				{
					test: /\.tsx?$/,
					loader: 'ts-loader'
				},
				{
					test: /\.(c|le)ss$/,
					use: [
						MiniCssExtractPlugin.loader,
						'css-loader',
						{
							loader: 'less-loader',
							options: {
								lessOptions: {
									javascriptEnabled: true
								}
							}
						}
					]
				}
			]
		},
		resolve: {
			extensions: ['.tsx', '.ts', '.js']
		},
		plugins: [
			new HtmlWebpackPlugin({
				title: 'DOJ',
				inject: 'body',
				favicon: 'web/logo.png',
				meta: {
					author: packageJson.author,
					description: packageJson.description,
					keywords: packageJson.keywords.join(',')
				}
			}),
			new WebpackCdnPlugin({
				modules: [
					{ name: 'moment', path: `min/moment.min.js` },
					{ name: 'axios', path: `dist/axios${min}.js` },
					{ name: 'ace-builds', var: 'ace', paths: [`src-min-noconflict/ace.js`, `src-min-noconflict/ext-static_highlight.js`] },
					{ name: 'katex', path: `dist/katex${min}.js`, style: `dist/katex${min}.css` },
					{ name: 'socket.io-client', var: 'io', path: 'dist/socket.io.js' },
					{ name: 'react', var: 'React', path: `umd/react.${reactMode}.js` },
					{ name: 'react-dom', var: 'ReactDOM', path: `umd/react-dom.${reactMode}.js` },
					{ name: 'react-router-dom', var: 'ReactRouterDOM', path: `umd/react-router-dom${min}.js` },
					{ name: 'react-markdown', var: 'ReactMarkdown', path: 'umd/react-markdown.js' },
					{ name: 'antd', path: `dist/antd${min}.js`, style: `dist/antd${min}.css` }
				],
				prod: argv.mode === 'production',
				publicPath: '/node_modules'
			}),
			new MiniCssExtractPlugin({
				filename: '[name].[chunkhash:8].css'
			})
		],
		devtool: dev && 'inline-source-map',
		devServer: {
			historyApiFallback: true,
			proxy: {
				'/api': {
					secure: false,
					changeOrigin: true,
					target: argv.server || `http://localhost:${config.get('port')}`
				},
				'/socket.io': {
					ws: true,
					secure: false,
					changeOrigin: true,
					target: argv.server || `ws://localhost:${config.get('port')}`
				}
			}
		},
		optimization: {
			minimize: argv.mode === 'production',
			minimizer: [new CssMinimizerPlugin(), '...']
		}
	}
}
<commit_msg>update<commit_after>const config = require('config')
const WebpackCdnPlugin = require('webpack-cdn-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const packageJson = require('./package.json')

module.exports = (_env, argv) => {
	const dev = argv.mode === 'development'
	const reactMode = dev ? 'development' : 'production.min'
	const min = dev ? '' : '.min'

	return {
		entry: {
			app: './web'
		},
		output: {
			publicPath: '/',
			filename: '[name].[chunkhash:8].js'
		},
		module: {
			rules: [
				{
					test: /\.tsx?$/,
					loader: 'ts-loader'
				},
				{
					test: /\.(c|le)ss$/,
					use: [
						MiniCssExtractPlugin.loader,
						'css-loader',
						{
							loader: 'less-loader',
							options: {
								lessOptions: {
									javascriptEnabled: true
								}
							}
						}
					]
				}
			]
		},
		resolve: {
			extensions: ['.tsx', '.ts', '.js']
		},
		plugins: [
			new HtmlWebpackPlugin({
				title: 'DOJ',
				inject: 'body',
				favicon: 'web/logo.png',
				meta: {
					author: packageJson.author,
					description: packageJson.description,
					keywords: packageJson.keywords.join(',')
				}
			}),
			new WebpackCdnPlugin({
				modules: [
					{ name: 'moment', path: `min/moment.min.js` },
					{ name: 'axios', path: `dist/axios${min}.js` },
					{ name: 'ace-builds', var: 'ace', paths: [`src-min-noconflict/ace.js`, `src-min-noconflict/ext-static_highlight.js`] },
					{ name: 'katex', path: `dist/katex${min}.js`, style: `dist/katex${min}.css` },
					{ name: 'socket.io-client', var: 'io', path: 'dist/socket.io.js' },
					{ name: 'react', var: 'React', path: `umd/react.${reactMode}.js` },
					{ name: 'react-dom', var: 'ReactDOM', path: `umd/react-dom.${reactMode}.js` },
					{ name: 'react-router-dom', var: 'ReactRouterDOM', path: `umd/react-router-dom${min}.js` },
					{ name: 'react-markdown', var: 'ReactMarkdown', path: 'umd/react-markdown.js' },
					{ name: 'antd', path: `dist/antd${min}.js`, style: `dist/antd${min}.css` }
				],
				prod: argv.mode === 'production',
				publicPath: '/node_modules'
			}),
			new MiniCssExtractPlugin({
				filename: '[name].[chunkhash:8].css'
			})
		],
		devtool: dev && 'inline-source-map',
		devServer: {
			historyApiFallback: true,
			proxy: {
				'/api': {
					secure: false,
					changeOrigin: true,
					target: `http://localhost:${config.get('port')}`
				},
				'/socket.io': {
					ws: true,
					secure: false,
					changeOrigin: true,
					target: `ws://localhost:${config.get('port')}`
				}
			}
		},
		optimization: {
			minimize: argv.mode === 'production',
			minimizer: [new CssMinimizerPlugin(), '...']
		}
	}
}
<|endoftext|>


<commit_before>var webpack = require("webpack");

var config = {
    entry: [
        "webpack-dev-server/client?http://localhost:3000",
        "webpack/hot/only-dev-server",
        "./src/entry.jsx"
    ],
    output: {
        path: __dirname,
        filename: "build/bundle.js"
    },
    module: {
        loaders: [{
            loader: "style!css",
            test: /\.css$/
        }, {
            loaders: ["react-hot", "babel-loader"],
            test: /\.jsx?$/,
            exclude: /node_modules/
        }]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin()
    ]
};

module.exports = config;
<commit_msg>added devtool property to the webpack.config<commit_after>var webpack = require("webpack");

var config = {
    devtool: "eval", // "source-map" if debug, "eval" if speed up
    entry: [
        "webpack-dev-server/client?http://localhost:3000",
        "webpack/hot/only-dev-server",
        "./src/entry.jsx"
    ],
    output: {
        path: __dirname,
        filename: "build/bundle.js"
    },
    module: {
        loaders: [{
            loader: "style!css",
            test: /\.css$/
        }, {
            loaders: ["react-hot", "babel-loader"],
            test: /\.jsx?$/,
            exclude: /node_modules/
        }]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin()
    ]
};

module.exports = config;
<|endoftext|>


<commit_before>const path = require('path');

let config = {
  entry: {
    tutorial: "./src/tutorial/index.tsx",
  },
  output: {
    path: path.join(__dirname, "./app/assets/javascripts/build"),
    filename: "[name].js",
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"],
    modules: [
      "node_modules",
      path.resolve("./src"),
    ],
  },
  module: {
    rules: [{
      test: /\.tsx?$/,
      use: [{
        loader: "ts-loader"
      }]
    }]
  }
};

if(process.env.NODE_ENV === "development") {
  Object.assign(config, {
    devtool: "source-map",
  });
}

module.exports = config;
<commit_msg>fix #54<commit_after>const path = require('path');

let config = {
  entry: {
    tutorial: "./src/tutorial/index.tsx",
  },
  output: {
    path: path.join(__dirname, "./app/assets/javascripts/build"),
    filename: "[name].js",
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"],
    modules: [
      "node_modules",
      path.resolve("./src"),
    ],
  },
  module: {
    rules: [{
      test: /\.tsx?$/,
      use: [{
        loader: "ts-loader"
      }]
    }]
  }
};

if (process.env.NODE_ENV === "development") {
  Object.assign(config, {
    devtool: "source-map",
  });
}

module.exports = config;
<|endoftext|>


<commit_before>/*
config for webpack. Will be used in
the Gulpfile for building our app.
Does not need gulp in order to do so,
but we use gulp to orchestrate
 */
module.exports = {
  output: {
    filename: 'bundle.js'
  },

  devtool: 'sourcemap',

  module: {
    loaders: [
      { test: /\.html$/, loader: 'raw' },
      { test: /\.styl$/, loader: 'style!css!stylus' },
      { test: /\.css/, loader: 'style!css' },
      { test: /\.js$/, loader: 'babel?stage=1', exclude: [/client\/lib/, /node_modules/, /\.spec\.js/] }
    ]
  },

  stylus: {
    use: [require('jeet')(), require('rupture')()]
  }
};
<commit_msg>Remove the stage option<commit_after>/*
config for webpack. Will be used in
the Gulpfile for building our app.
Does not need gulp in order to do so,
but we use gulp to orchestrate
 */
module.exports = {
  output: {
    filename: 'bundle.js'
  },

  devtool: 'sourcemap',

  module: {
    loaders: [
      { test: /\.html$/, loader: 'raw' },
      { test: /\.styl$/, loader: 'style!css!stylus' },
      { test: /\.css/, loader: 'style!css' },
      { test: /\.js$/, loader: 'babel', exclude: [/client\/lib/, /node_modules/, /\.spec\.js/] }
    ]
  },

  stylus: {
    use: [require('jeet')(), require('rupture')()]
  }
};
<|endoftext|>


<commit_before>var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
var autoprefixer = require('autoprefixer');

var cssExtractor = new ExtractTextWebpackPlugin('styles/[name].css');
var lifecycleEvent = process.env.npm_lifecycle_event;

var config = {
    entry: './src/app.jsx',
    output: {
        path: __dirname + '/public',
        filename: 'js/app.js'
    },
    devtool: 'source-map',
    module: {
		preLoaders: [
            {
                test: /\.jsx?$/,
                loaders: ['eslint'],
                exclude: /node_modules/
            }
        ],
        loaders: [
            {    // CSS/Sass loader config
				key: 'STYLES',
                test: /\.s?css$/,
                loaders: ['css', 'postcss', 'sass']
            },
            {    // ES6 loader config
				key: 'JS',
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loaders: ['babel']
            },
            {
				key: 'FONTS',
                test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
                loaders: ['file?name=fonts/[name].[ext]']
            }
        ]
    },
	postcss: [
		autoprefixer({ browsers: ['last 3 versions'] })	// Automatically adds vendor prefixes for x browser versions (and all vendors). :D
	],
    plugins: [
        new HtmlWebpackPlugin({        // Plugin to inject source references into index.html (note: doesn't need handlebars)
            title: 'Webpack Build',
            template: './src/index.html'
        })
    ],
    devServer: {
        historyApiFallback: true,
        contentBase: './public',
        proxy: [
            {
                path: new RegExp('/api/(.*)'),
                changeOrigin: true,
                prependPath: false,
                xfwd: true,
                target: 'https://yourApiDomain.net/'
            }
        ]
    }
}

switch (lifecycleEvent) {
	case 'build':
		// build specific mutations

		config.module.loaders.forEach(item => {
			switch (item.key) {
				case 'STYLES':
					item.loader = cssExtractor.extract(item.loaders);
					delete item.loaders;
					break;
			}
		})

		config.plugins.push(cssExtractor);

		config.plugins.push(new webpack.DefinePlugin({
			'process.env.NODE_ENV': '"production"'
		}));

		config.plugins.push(new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            sourceMap: true,
            minimize: true
        }));

		config.plugins.push(new CleanWebpackPlugin(['public/fonts', 'public/js', 'public/styles', 'public/index.html']));

		break;
	default:
		// in all other cases
		config.module.loaders.forEach(item => {
			switch (item.key) {
				case 'STYLES':
					item.loaders.unshift('style');
					break;
			}
		})

		config.plugins.push(new webpack.DefinePlugin({
			'process.env.NODE_ENV': '"development"'
		}));
		break;
}

module.exports = config;
<commit_msg>added documentation<commit_after>var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
var autoprefixer = require('autoprefixer');

var cssExtractor = new ExtractTextWebpackPlugin('styles/[name].css');
var lifecycleEvent = process.env.npm_lifecycle_event;

/*
    INITIAL CONFIG
 */

var config = {
    entry: './src/app.jsx',
    output: {
        path: __dirname + '/public',
        filename: 'js/app.js'
    },
    devtool: 'source-map',
    module: {
		preLoaders: [
            {
                test: /\.jsx?$/,
                loaders: ['eslint'],
                exclude: /node_modules/
            }
        ],
        loaders: [
            {    // CSS/Sass loader config
				key: 'STYLES',
                test: /\.s?css$/,
                loaders: ['css', 'postcss', 'sass']
            },
            {    // ES6 loader config
				key: 'JS',
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loaders: ['babel']
            },
            {
				key: 'FONTS',
                test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
                loaders: ['file?name=fonts/[name].[ext]']
            }
        ]
    },
	postcss: [
		autoprefixer({ browsers: ['last 3 versions'] })	// Automatically adds vendor prefixes for x browser versions (and all vendors). :D
	],
    plugins: [
        new HtmlWebpackPlugin({        // Plugin to inject source references into index.html (note: doesn't need handlebars)
            title: 'Webpack Build',
            template: './src/index.html'
        })
    ],
    devServer: {
        historyApiFallback: true,
        contentBase: './public',
        proxy: [
            {
                path: new RegExp('/api/(.*)'),
                changeOrigin: true,
                prependPath: false,
                xfwd: true,
                target: 'https://yourApiDomain.net/'
            }
        ]
    }
}

/*
    OVERRIDE THE INITIAL CONFIG BASED ON OUR ENVIRONMENT
 */
switch (lifecycleEvent) {
    /*
        PRODUCTION CONFIGURATION
     */
	case 'build':
		// build specific mutations

		config.module.loaders.forEach(item => {
			switch (item.key) {
				case 'STYLES':
					item.loader = cssExtractor.extract(item.loaders);
					delete item.loaders;
					break;
			}
		})

		config.plugins.push(cssExtractor);

		config.plugins.push(new webpack.DefinePlugin({
			'process.env.NODE_ENV': '"production"'
		}));

		config.plugins.push(new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            sourceMap: true,
            minimize: true
        }));

		config.plugins.push(new CleanWebpackPlugin(['public/fonts', 'public/js', 'public/styles', 'public/index.html']));

		break;
	default:
		/*
    		DEVELOPMENT CONFIGURATION
		 */
		config.module.loaders.forEach(item => {
			switch (item.key) {
				case 'STYLES':
					item.loaders.unshift('style');
					break;
			}
		})

		config.plugins.push(new webpack.DefinePlugin({
			'process.env.NODE_ENV': '"development"'
		}));
		break;
}

module.exports = config;
<|endoftext|>


<commit_before>const pkg = require('./package.json');

const fs = require('fs');
const path = require('path');

const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
const SassLintPlugin = require('sasslint-webpack-plugin');
const UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
const customLoader = require('custom-loader');

const archiver = require('archiver');

const extractSrc = new ExtractTextPlugin('dist/vizabi.css');
const extractPreview = new ExtractTextPlugin('preview/assets/css/main.css');

const __PROD__ = process.env.NODE_ENV === 'production';
const __FIX__ = !!process.env.FIX;
const timestamp = new Date();

const sep = '\\' + path.sep;
const stats = {
  colors: true,
  hash: false,
  version: false,
  timings: true,
  assets: false,
  chunks: false,
  modules: false,
  reasons: true,
  children: false,
  source: false,
  errors: true,
  errorDetails: true,
  warnings: true,
  publicPath: false
};

function AfterBuildPlugin(callback) {
  this.callback = callback;
}
AfterBuildPlugin.prototype.apply = function (compiler) {
  compiler.plugin('done', this.callback);
};

customLoader.loaders = {
  ['config-loader'](source) {
    this.cacheable && this.cacheable();

    const value = typeof source === 'string' ? JSON.parse(source) : source;
    this.value = [value];
    return `var VIZABI_MODEL = ${JSON.stringify(value, undefined, '  ')};`;
  }
};

const plugins = [
  new CleanWebpackPlugin(['build']),
  extractSrc,
  extractPreview,
  new CopyWebpackPlugin([
    {
      from: '.data/',
      to: 'preview/data/'
    },
    {
      from: 'preview/assets/js/',
      to: 'preview/assets/js/'
    },
    {
      from: 'src/assets/translation/',
      to: 'preview/assets/translation/'
    }
  ]),
  new CopyWebpackPlugin([
    {
      from: 'src/assets/translation/',
      to: 'dist/assets/translation/'
    },
    {
      from: 'src/assets/cursors/',
      to: 'dist/assets/cursors/'
    }
  ]),
  new OpenBrowserPlugin({
    url: 'http://localhost:8080/preview/'
  }),
  new SassLintPlugin({
    quiet: false,
    syntax: 'scss',
    glob: 'src/**/*.s?(a|c)ss',
    ignorePlugins: ['extract-text-webpack-plugin']
  }),
  new webpack.DefinePlugin({
    __VERSION: JSON.stringify(pkg.version),
    __BUILD: +timestamp
  })
];

if (__PROD__) {
  plugins.push(
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compressor: {
        screw_ie8: true,
        warnings: false
      },
      mangle: {
        screw_ie8: true
      },
      output: {
        comments: false,
        screw_ie8: true
      }
    }),
    new UnminifiedWebpackPlugin(),
    new AfterBuildPlugin(() => {
      fs.mkdirSync(path.resolve(__dirname, 'build', 'download'));

      const archive = archiver('zip');
      const files = [
        'vizabi.css',
        'vizabi.min.js',
        'vizabi.js'
      ];

      files.forEach(name =>
        archive.append(
          fs.createReadStream(path.resolve('build', 'dist', name)),
          { name }
        )
      );

      archive.pipe(
        fs.createWriteStream(path.resolve('build', 'download', 'vizabi.zip'))
      );
      archive.glob('**/*', { cwd: 'src/assets/cursors', dot: true }, { prefix: 'assets/cursors' });
      archive.glob('en.json', { cwd: 'src/assets/translation', dot: true }, { prefix: 'assets/translation' });
      archive.finalize();
    }),
    new webpack.BannerPlugin({
      banner: [
        '/**',
        ' * ' + pkg.name + ' - ' + pkg.description,
        ' * @version v' + pkg.version,
        ' * @build timestamp ' + timestamp,
        ' * @link ' + pkg.homepage,
        ' * @license ' + pkg.license,
        ' */',
        ''
      ].join('\n'),
      raw: true
    })
  )
}

const loaders = [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    loaders: [
      {
        loader: 'babel-loader',
        query: {
          cacheDirectory: !__PROD__,
          presets: ['es2015']
        }
      },
      // {
      //   loader: 'eslint-loader',
      //   options: {
      //     fix: __FIX__
      //   }
      // }
    ]
  },
  {
    test: /\.scss$/,
    include: [
      path.resolve(__dirname, 'src')
    ],
    loader: extractSrc.extract([
      {
        loader: 'css-loader',
        options: {
          minimize: __PROD__,
          sourceMap: true
        }
      },
      {
        loader: 'postcss-loader'
      },
      {
        loader: 'sass-loader'
      }
    ])
  },
  {
    test: /\.scss$/,
    include: [
      path.resolve(__dirname, 'preview')
    ],
    loader: extractPreview.extract(['css-loader', 'sass-loader'])
  },
  {
    test: /\.cur$/,
    loader: 'file-loader',
    query: {
      publicPath: path => path.split('/').slice(1).join('/'),
      name: 'preview/assets/cursors/[name].[ext]'
    }
  },
  {
    test: /\.pug$/,
    loaders: [
      'file-loader?name=[path][name].html',
      'pug-html-loader?exports=false'
    ]
  },
  {
    test: /\.css$/,
    include: [
      path.resolve(__dirname, 'node_modules')
    ],
    loader: 'file-loader',
    query: {
      name: 'preview/assets/vendor/css/[name].[ext]'
    }
  },
  {
    test: /\.(otf|eot|svg|ttf|woff2?)$/,
    include: [
      path.resolve(__dirname, 'node_modules')
    ],
    loader: 'file-loader',
    query: {
      name: 'preview/assets/vendor/fonts/[name].[ext]'
    }
  },
  {
    test: /(d3|\.web|vizabi-ddfcsv-reader)\.js$/, // TODO: we need another way to extract vendor files
    include: [
      path.resolve(__dirname, 'node_modules')
    ],
    loader: 'file-loader',
    query: {
      name: 'preview/assets/vendor/js/[1]/[name].[ext]',
      regExp: new RegExp(`${sep}node_modules${sep}([^${sep}]+?)${sep}`)
    }
  },
  {
    test: /\.html$/,
    include: [path.resolve(__dirname, 'src')],
    loader: 'html-loader'
  },
  {
    test: /\.json$/,
    include: [
      path.resolve(__dirname, 'node_modules')
    ],
    loaders: [
      'file-loader?name=preview/assets/js/toolconfigs/[name].js',
      'custom-loader?name=config-loader'
    ]
  },
];

module.exports = {
  devtool: 'source-map',

  entry: {
    'dist/vizabi': './src/vizabi-gapminder',
    'preview': './preview/index'
  },

  output: {
    path: path.resolve(__dirname, 'build'),
    filename: __PROD__ ? '[name].min.js' : '[name].js',
    library: 'Vizabi',
    libraryTarget: 'umd',
    umdNamedDefine: true
  },

  resolve: {
    modules: [
      path.resolve(__dirname, 'src'),
      'node_modules'
    ]
  },

  module: {
    loaders
  },

  plugins,

  stats,
  devServer: {
    stats,
    host: '0.0.0.0'
  }
};
<commit_msg>Modify webpack config to make preview page work<commit_after>const pkg = require('./package.json');

const fs = require('fs');
const path = require('path');

const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
const SassLintPlugin = require('sasslint-webpack-plugin');
const UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
const customLoader = require('custom-loader');

const archiver = require('archiver');

const extractSrc = new ExtractTextPlugin('dist/vizabi.css');
const extractPreview = new ExtractTextPlugin('preview/assets/css/main.css');

const __PROD__ = process.env.NODE_ENV === 'production';
const __FIX__ = !!process.env.FIX;
const timestamp = new Date();

const sep = '\\' + path.sep;
const stats = {
  colors: true,
  hash: false,
  version: false,
  timings: true,
  assets: false,
  chunks: false,
  modules: false,
  reasons: true,
  children: false,
  source: false,
  errors: true,
  errorDetails: true,
  warnings: true,
  publicPath: false
};

function AfterBuildPlugin(callback) {
  this.callback = callback;
}
AfterBuildPlugin.prototype.apply = function(compiler) {
  compiler.plugin('done', this.callback);
};

customLoader.loaders = {
  ['config-loader'](source) {
    this.cacheable && this.cacheable();

    const value = typeof source === 'string' ? JSON.parse(source) : source;
    this.value = [value];
    return `var VIZABI_MODEL = ${JSON.stringify(value, undefined, '  ')};`;
  }
};

const plugins = [
  new CleanWebpackPlugin(['build']),
  extractSrc,
  extractPreview,
  new CopyWebpackPlugin([
    //   {
    //     from: '.data/',
    //     to: 'preview/data/'
    //   },
    //   {
    //     from: 'preview/assets/js/',
    //     to: 'preview/assets/js/'
    //   },
    // TODO: replace with file-loader
    {
      from: path.resolve(__dirname, 'src', 'assets', 'translation'),
      to: path.resolve(__dirname, 'build', 'dist', 'assets', 'translation'),
    }
  ]),
  // new CopyWebpackPlugin([
  //   {
  //     from: 'src/assets/translation/',
  //     to: 'dist/assets/translation/'
  //   },
  //   {
  //     from: 'src/assets/cursors/',
  //     to: 'dist/assets/cursors/'
  //   }
  // ]),
  // new OpenBrowserPlugin({
  //   url: 'http://localhost:8080/preview/'
  // }),
  new SassLintPlugin({
    quiet: false,
    syntax: 'scss',
    glob: 'src/**/*.s?(a|c)ss',
    ignorePlugins: ['extract-text-webpack-plugin']
  }),
  new webpack.DefinePlugin({
    __VERSION: JSON.stringify(pkg.version),
    __BUILD: +timestamp
  })
];

if (__PROD__) {
  plugins.push(
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compressor: {
        screw_ie8: true,
        warnings: false
      },
      mangle: {
        screw_ie8: true
      },
      output: {
        comments: false,
        screw_ie8: true
      }
    }),
    new UnminifiedWebpackPlugin(),
    new AfterBuildPlugin(() => {
      fs.mkdirSync(path.resolve(__dirname, 'build', 'download'));

      const archive = archiver('zip');
      const files = [
        'vizabi.css',
        'vizabi.min.js',
        'vizabi.js'
      ];

      files.forEach(name =>
        archive.append(
          fs.createReadStream(path.resolve('build', 'dist', name)),
          { name }
        )
      );

      archive.pipe(
        fs.createWriteStream(path.resolve('build', 'download', 'vizabi.zip'))
      );
      archive.glob('**/*', { cwd: 'src/assets/cursors', dot: true }, { prefix: 'assets/cursors' });
      archive.glob('en.json', { cwd: 'src/assets/translation', dot: true }, { prefix: 'assets/translation' });
      archive.finalize();
    }),
    new webpack.BannerPlugin({
      banner: [
        '/**',
        ' * ' + pkg.name + ' - ' + pkg.description,
        ' * @version v' + pkg.version,
        ' * @build timestamp ' + timestamp,
        ' * @link ' + pkg.homepage,
        ' * @license ' + pkg.license,
        ' */',
        ''
      ].join('\n'),
      raw: true
    })
  )
}

const loaders = [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    loaders: [
      {
        loader: 'babel-loader',
        query: {
          cacheDirectory: !__PROD__,
          presets: ['es2015']
        }
      },
      // {
      //   loader: 'eslint-loader',
      //   options: {
      //     fix: __FIX__
      //   }
      // }
    ]
  },
  {
    test: /\.scss$/,
    include: [
      path.resolve(__dirname, 'src')
    ],
    loader: extractSrc.extract([
      {
        loader: 'css-loader',
        options: {
          minimize: __PROD__,
          sourceMap: true
        }
      },
      {
        loader: 'postcss-loader'
      },
      {
        loader: 'sass-loader'
      }
    ])
  },
  {
    test: /\.scss$/,
    include: [
      path.resolve(__dirname, 'preview')
    ],
    loader: extractPreview.extract(['css-loader', 'sass-loader'])
  },
  {
    test: /\.cur$/,
    loader: 'file-loader',
    query: {
      publicPath: path => path.split('/').slice(1).join('/'),
      name: 'preview/assets/cursors/[name].[ext]'
    }
  },
  {
    test: /\.pug$/,
    loaders: [
      'file-loader?name=[path][name].html',
      'pug-html-loader?exports=false'
    ]
  },
  {
    test: /\.css$/,
    include: [
      path.resolve(__dirname, 'node_modules')
    ],
    loader: 'file-loader',
    query: {
      name: 'preview/assets/vendor/css/[name].[ext]'
    }
  },
  {
    test: /\.(otf|eot|svg|ttf|woff2?)$/,
    include: [
      path.resolve(__dirname, 'node_modules')
    ],
    loader: 'file-loader',
    query: {
      name: 'preview/assets/vendor/fonts/[name].[ext]'
    }
  },
  {
    test: /(d3|\.web|vizabi-ddfcsv-reader)\.js$/, // TODO: we need another way to extract vendor files
    include: [
      path.resolve(__dirname, 'node_modules')
    ],
    loader: 'file-loader',
    query: {
      name: 'preview/assets/vendor/js/[1]/[name].[ext]',
      regExp: new RegExp(`${sep}node_modules${sep}([^${sep}]+?)${sep}`)
    }
  },
  {
    test: /\.html$/,
    include: [path.resolve(__dirname, 'src')],
    loader: 'html-loader'
  },
  {
    test: /\.json$/,
    include: [
      path.resolve(__dirname, 'node_modules')
    ],
    loaders: [
      'file-loader?name=preview/assets/js/toolconfigs/[name].js',
      'custom-loader?name=config-loader'
    ]
  },
];

module.exports = {
  devtool: 'source-map',

  entry: {
    'dist/vizabi': path.resolve(__dirname, 'src', 'vizabi-gapminder'),
    // 'preview': './preview/index'
  },

  output: {
    path: path.resolve(__dirname, 'build'),
    filename: __PROD__ ? '[name].min.js' : '[name].js',
    library: 'Vizabi',
    libraryTarget: 'umd',
    umdNamedDefine: true
  },

  resolveLoader: {
    modules: [
      'web_loaders',
      'web_modules',
      'node_loaders',
      'node_modules',
      path.resolve(__dirname, 'node_modules'),
    ],
  },
  resolve: {
    modules: [
      path.resolve(__dirname, 'src'),
      'node_modules'
    ]
  },

  module: {
    loaders
  },

  plugins,

  // stats,
  // devServer: {
  //   stats,
  //   host: '0.0.0.0'
  // }
};
<|endoftext|>


<commit_before>/* eslint-disable */

const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const WebpackBuildNotifierPlugin = require("webpack-build-notifier");
const ManifestPlugin = require("webpack-manifest-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const LessPluginAutoPrefix = require("less-plugin-autoprefix");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
  .BundleAnalyzerPlugin;
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");

const path = require("path");

function optionalRequire(module, defaultReturn = undefined) {
  try {
    require.resolve(module);
  } catch (e) {
    if (e && e.code === "MODULE_NOT_FOUND") {
      // Module was not found, return default value if any
      return defaultReturn;
    }
    throw e;
  }
  return require(module);
}

// Load optionally configuration object (see scripts/README)
const CONFIG = optionalRequire("./scripts/config", {});

const isProduction = process.env.NODE_ENV === "production";
const isDevelopment = !isProduction;
const isHotReloadingEnabled = isDevelopment && process.env.HOT_RELOAD === "true";

const redashBackend = process.env.REDASH_BACKEND || "http://localhost:5000";
const baseHref = CONFIG.baseHref || "/";
const staticPath = CONFIG.staticPath || "/static/";
const htmlTitle = CONFIG.title || "Redash";

const basePath = path.join(__dirname, "client");
const appPath = path.join(__dirname, "client", "app");

const extensionsRelativePath =
  process.env.EXTENSIONS_DIRECTORY || path.join("client", "app", "extensions");
const extensionPath = path.join(__dirname, extensionsRelativePath);

// Function to apply configuration overrides (see scripts/README)
function maybeApplyOverrides(config) {
  const overridesLocation =
    process.env.REDASH_WEBPACK_OVERRIDES || "./scripts/webpack/overrides";
  const applyOverrides = optionalRequire(overridesLocation);
  if (!applyOverrides) {
    return config;
  }
  console.info("Custom overrides found. Applying them...");
  const newConfig = applyOverrides(config);
  console.info("Custom overrides applied successfully.");
  return newConfig;
}

const config = {
  mode: isProduction ? "production" : "development",
  entry: {
    app: [
      "./client/app/index.js",
      "./client/app/assets/less/main.less",
      "./client/app/assets/less/ant.less"
    ],
    server: ["./client/app/assets/less/server.less"]
  },
  output: {
    path: path.join(basePath, "./dist"),
    filename: isProduction ? "[name].[chunkhash].js" : "[name].js",
    publicPath: staticPath
  },
  resolve: {
    symlinks: false,
    extensions: [".js", ".jsx", ".ts", ".tsx"],
    alias: {
      "@": appPath,
      extensions: extensionPath
    }
  },
  plugins: [
    new WebpackBuildNotifierPlugin({ title: "Redash" }),
    // bundle only default `moment` locale (`en`)
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
    new HtmlWebpackPlugin({
      template: "./client/app/index.html",
      filename: "index.html",
      excludeChunks: ["server"],
      release: process.env.BUILD_VERSION || "dev",
      staticPath,
      baseHref,
      title: htmlTitle
    }),
    new HtmlWebpackPlugin({
      template: "./client/app/multi_org.html",
      filename: "multi_org.html",
      excludeChunks: ["server"]
    }),
    isProduction &&
      new MiniCssExtractPlugin({
        filename: "[name].[chunkhash].css"
      }),
    new ManifestPlugin({
      fileName: "asset-manifest.json",
      publicPath: ""
    }),
    new CopyWebpackPlugin([
      { from: "client/app/assets/robots.txt" },
      { from: "client/app/unsupported.html" },
      { from: "client/app/unsupportedRedirect.js" },
      { from: "client/app/assets/css/*.css", to: "styles/", flatten: true },
      { from: "client/app/assets/fonts", to: "fonts/" }
    ]),
    isHotReloadingEnabled && new ReactRefreshWebpackPlugin({ overlay: false })
  ].filter(Boolean),
  optimization: {
    splitChunks: {
      chunks: chunk => {
        return chunk.name != "server";
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.(t|j)sx?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: require.resolve("babel-loader"),
            options: {
              plugins: [
                isHotReloadingEnabled && require.resolve("react-refresh/babel")
              ].filter(Boolean)
            }
          },
          require.resolve("eslint-loader")
        ]
      },
      {
        test: /\.html$/,
        exclude: [/node_modules/, /index\.html/, /multi_org\.html/],
        use: [
          {
            loader: "raw-loader"
          }
        ]
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: isHotReloadingEnabled ? "style-loader" : MiniCssExtractPlugin.loader
          },
          {
            loader: "css-loader",
            options: {
              minimize: process.env.NODE_ENV === "production"
            }
          }
        ]
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: isHotReloadingEnabled ? "style-loader" : MiniCssExtractPlugin.loader
          },
          {
            loader: "css-loader",
            options: {
              minimize: isProduction
            }
          },
          {
            loader: "less-loader",
            options: {
              plugins: [
                new LessPluginAutoPrefix({ browsers: ["last 3 versions"] })
              ],
              javascriptEnabled: true
            }
          }
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        use: [
          {
            loader: "file-loader",
            options: {
              context: path.resolve(appPath, "./assets/images/"),
              outputPath: "images/",
              name: "[path][name].[ext]"
            }
          }
        ]
      },
      {
        test: /\.geo\.json$/,
        type: "javascript/auto",
        use: [
          {
            loader: "file-loader",
            options: {
              outputPath: "data/",
              name: "[hash:7].[name].[ext]"
            }
          }
        ]
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 10000,
              name: "fonts/[name].[hash:7].[ext]"
            }
          }
        ]
      }
    ]
  },
  devtool: isProduction ? "source-map" : "cheap-eval-module-source-map",
  stats: {
    children: false,
    modules: false,
    chunkModules: false
  },
  watchOptions: {
    ignored: /\.sw.$/
  },
  devServer: {
    inline: true,
    index: "/static/index.html",
    historyApiFallback: {
      index: "/static/index.html",
      rewrites: [{ from: /./, to: "/static/index.html" }]
    },
    contentBase: false,
    publicPath: staticPath,
    proxy: [
      {
        context: [
          "/login",
          "/logout",
          "/invite",
          "/setup",
          "/status.json",
          "/api",
          "/oauth"
        ],
        target: redashBackend + "/",
        changeOrigin: false,
        secure: false
      },
      {
        context: path => {
          // CSS/JS for server-rendered pages should be served from backend
          return /^\/static\/[a-z]+\.[0-9a-fA-F]+\.(css|js)$/.test(path);
        },
        target: redashBackend + "/",
        changeOrigin: true,
        secure: false
      }
    ],
    stats: {
      modules: false,
      chunkModules: false
    },
    hot: isHotReloadingEnabled
  },
  performance: {
    hints: false
  }
};

if (process.env.DEV_SERVER_HOST) {
  config.devServer.host = process.env.DEV_SERVER_HOST;
}

if (process.env.BUNDLE_ANALYZER) {
  config.plugins.push(new BundleAnalyzerPlugin());
}

module.exports = maybeApplyOverrides(config);
<commit_msg>Fix disabled hot reload flow (#5306)<commit_after>/* eslint-disable */

const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const WebpackBuildNotifierPlugin = require("webpack-build-notifier");
const ManifestPlugin = require("webpack-manifest-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const LessPluginAutoPrefix = require("less-plugin-autoprefix");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
  .BundleAnalyzerPlugin;
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");

const path = require("path");

function optionalRequire(module, defaultReturn = undefined) {
  try {
    require.resolve(module);
  } catch (e) {
    if (e && e.code === "MODULE_NOT_FOUND") {
      // Module was not found, return default value if any
      return defaultReturn;
    }
    throw e;
  }
  return require(module);
}

// Load optionally configuration object (see scripts/README)
const CONFIG = optionalRequire("./scripts/config", {});

const isProduction = process.env.NODE_ENV === "production";
const isDevelopment = !isProduction;
const isHotReloadingEnabled =
  isDevelopment && process.env.HOT_RELOAD === "true";

const redashBackend = process.env.REDASH_BACKEND || "http://localhost:5000";
const baseHref = CONFIG.baseHref || "/";
const staticPath = CONFIG.staticPath || "/static/";
const htmlTitle = CONFIG.title || "Redash";

const basePath = path.join(__dirname, "client");
const appPath = path.join(__dirname, "client", "app");

const extensionsRelativePath =
  process.env.EXTENSIONS_DIRECTORY || path.join("client", "app", "extensions");
const extensionPath = path.join(__dirname, extensionsRelativePath);

// Function to apply configuration overrides (see scripts/README)
function maybeApplyOverrides(config) {
  const overridesLocation =
    process.env.REDASH_WEBPACK_OVERRIDES || "./scripts/webpack/overrides";
  const applyOverrides = optionalRequire(overridesLocation);
  if (!applyOverrides) {
    return config;
  }
  console.info("Custom overrides found. Applying them...");
  const newConfig = applyOverrides(config);
  console.info("Custom overrides applied successfully.");
  return newConfig;
}

const config = {
  mode: isProduction ? "production" : "development",
  entry: {
    app: [
      "./client/app/index.js",
      "./client/app/assets/less/main.less",
      "./client/app/assets/less/ant.less"
    ],
    server: ["./client/app/assets/less/server.less"]
  },
  output: {
    path: path.join(basePath, "./dist"),
    filename: isProduction ? "[name].[chunkhash].js" : "[name].js",
    publicPath: staticPath
  },
  resolve: {
    symlinks: false,
    extensions: [".js", ".jsx", ".ts", ".tsx"],
    alias: {
      "@": appPath,
      extensions: extensionPath
    }
  },
  plugins: [
    new WebpackBuildNotifierPlugin({ title: "Redash" }),
    // bundle only default `moment` locale (`en`)
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
    new HtmlWebpackPlugin({
      template: "./client/app/index.html",
      filename: "index.html",
      excludeChunks: ["server"],
      release: process.env.BUILD_VERSION || "dev",
      staticPath,
      baseHref,
      title: htmlTitle
    }),
    new HtmlWebpackPlugin({
      template: "./client/app/multi_org.html",
      filename: "multi_org.html",
      excludeChunks: ["server"]
    }),
    isProduction &&
      new MiniCssExtractPlugin({
        filename: "[name].[chunkhash].css"
      }),
    new ManifestPlugin({
      fileName: "asset-manifest.json",
      publicPath: ""
    }),
    new CopyWebpackPlugin([
      { from: "client/app/assets/robots.txt" },
      { from: "client/app/unsupported.html" },
      { from: "client/app/unsupportedRedirect.js" },
      { from: "client/app/assets/css/*.css", to: "styles/", flatten: true },
      { from: "client/app/assets/fonts", to: "fonts/" }
    ]),
    isHotReloadingEnabled && new ReactRefreshWebpackPlugin({ overlay: false })
  ].filter(Boolean),
  optimization: {
    splitChunks: {
      chunks: chunk => {
        return chunk.name != "server";
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.(t|j)sx?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: require.resolve("babel-loader"),
            options: {
              plugins: [
                isHotReloadingEnabled && require.resolve("react-refresh/babel")
              ].filter(Boolean)
            }
          },
          require.resolve("eslint-loader")
        ]
      },
      {
        test: /\.html$/,
        exclude: [/node_modules/, /index\.html/, /multi_org\.html/],
        use: [
          {
            loader: "raw-loader"
          }
        ]
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: isProduction ? MiniCssExtractPlugin.loader : "style-loader"
          },
          {
            loader: "css-loader",
            options: {
              minimize: process.env.NODE_ENV === "production"
            }
          }
        ]
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: isProduction ? MiniCssExtractPlugin.loader : "style-loader"
          },
          {
            loader: "css-loader",
            options: {
              minimize: isProduction
            }
          },
          {
            loader: "less-loader",
            options: {
              plugins: [
                new LessPluginAutoPrefix({ browsers: ["last 3 versions"] })
              ],
              javascriptEnabled: true
            }
          }
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        use: [
          {
            loader: "file-loader",
            options: {
              context: path.resolve(appPath, "./assets/images/"),
              outputPath: "images/",
              name: "[path][name].[ext]"
            }
          }
        ]
      },
      {
        test: /\.geo\.json$/,
        type: "javascript/auto",
        use: [
          {
            loader: "file-loader",
            options: {
              outputPath: "data/",
              name: "[hash:7].[name].[ext]"
            }
          }
        ]
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 10000,
              name: "fonts/[name].[hash:7].[ext]"
            }
          }
        ]
      }
    ]
  },
  devtool: isProduction ? "source-map" : "cheap-eval-module-source-map",
  stats: {
    children: false,
    modules: false,
    chunkModules: false
  },
  watchOptions: {
    ignored: /\.sw.$/
  },
  devServer: {
    inline: true,
    index: "/static/index.html",
    historyApiFallback: {
      index: "/static/index.html",
      rewrites: [{ from: /./, to: "/static/index.html" }]
    },
    contentBase: false,
    publicPath: staticPath,
    proxy: [
      {
        context: [
          "/login",
          "/logout",
          "/invite",
          "/setup",
          "/status.json",
          "/api",
          "/oauth"
        ],
        target: redashBackend + "/",
        changeOrigin: false,
        secure: false
      },
      {
        context: path => {
          // CSS/JS for server-rendered pages should be served from backend
          return /^\/static\/[a-z]+\.[0-9a-fA-F]+\.(css|js)$/.test(path);
        },
        target: redashBackend + "/",
        changeOrigin: true,
        secure: false
      }
    ],
    stats: {
      modules: false,
      chunkModules: false
    },
    hot: isHotReloadingEnabled
  },
  performance: {
    hints: false
  }
};

if (process.env.DEV_SERVER_HOST) {
  config.devServer.host = process.env.DEV_SERVER_HOST;
}

if (process.env.BUNDLE_ANALYZER) {
  config.plugins.push(new BundleAnalyzerPlugin());
}

module.exports = maybeApplyOverrides(config);
<|endoftext|>


<commit_before>'use strict'

// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development'

const path = require('path')

const { AotPlugin } = require('@ngtools/webpack')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const opener = require('opener')
const webpack = require('webpack')
const merge = require('webpack-merge')
const webpackKit = require('webpack-kit-nimedev')
const webpackEnv = require('./config/webpack-environment')

const PATHS = {
  src: path.join(__dirname, 'src'),
  dist: path.join(__dirname, 'dist'),
  images: path.join(__dirname, 'src/assets/images'),
  icons: path.join(__dirname, 'src/assets/icons'),
  fonts: path.join(__dirname, 'src/assets/fonts'),
  styles: path.join(__dirname, 'src/styles/index.css'),
  componentStyles: path.join(__dirname, 'src/app')
}

const common = merge([
  // Common settings
  {
    entry: {
      app: `${PATHS.src}/main.ts`,
      polyfills: `${PATHS.src}/polyfills.ts`
    },
    output: {
      path: PATHS.dist,
      filename: '[name].js'
    },

    // TypeScript loaders.
    module: {
      rules: [{
        test: /\.ts$/,
        include: PATHS.src,
        enforce: 'pre',

        use: 'tslint-loader'
      }, {
        test: /\.ts$/,
        include: PATHS.src,

        use: '@ngtools/webpack'
      }]
    },
    plugins: [
      new webpack.DefinePlugin(Object.assign(
        {},
        webpackEnv.defineEnvironment
      )),

      // Workaround for angular/angular#11580
      new webpack.ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)@angular/,
        PATHS.src
      ),
      new AotPlugin({
        entryModule: `${PATHS.src}/app/app.module#AppModule`,
        tsConfigPath: `${PATHS.src}/tsconfig.aot.json`,
        skipCodeGeneration: process.env.NODE_ENV === 'development'
      })
    ],
    resolve: {
      extensions: ['.ts', '.js', '.json', '.css']
    }
  },
  webpackKit.htmlPlugin({ template: './src/index.html' }, ['polyfills', 'vendor', 'app']),
  webpackKit.lintCSS({ files: 'src/**/*.css' }),
  webpackKit.loadHtml({ include: PATHS.src }),
  webpackKit.loadImages({
    include: PATHS.images,
    options: {
      name: './assets/images/[name].[hash].[ext]',
      limit: 25000
    }
  }),
  webpackKit.loadSvgSprite({
    include: PATHS.icons,
    options: {
      name: './assets/icons/[name].[hash].[ext]'
    }
  }),
  webpackKit.loadFonts({ include: PATHS.fonts }),
  webpackKit.loadAssets({ include: PATHS.src }),

  // Load css of components
  webpackKit.loadCSS({
    include: PATHS.componentStyles,
    useExportsLoader: true
  })
])

module.exports = ({ target }) => {
  // Return production configuration
  if (target === 'production') {
    return merge([
      common,
      {
        output: {
          filename: '[name].[chunkhash].js'
        },
        plugins: [
          new webpack.HashedModuleIdsPlugin(),
          new CleanWebpackPlugin([PATHS.dist], {
            // Without `root` CleanWebpackPlugin won't point to our
            // project and will fail to work.
            root: process.cwd()
          }),
          new webpack.optimize.UglifyJsPlugin({
            compress: {
              warnings: false
            }
          })
        ]
      },
      webpackKit.extractVendor(webpack, { chunks: ['app'] }),
      webpackKit.loadJS({ include: PATHS.src }),

      // Load global styles
      webpackKit.extractCSS({ include: PATHS.styles })
    ])
  }

  // Run opener
  opener(`http://${webpackEnv.host}:${webpackEnv.port}`)

  // Return development configurations
  return merge([
    common,
    {
      devtool: '#inline-source-map',
      plugins: [
        new webpack.NamedModulesPlugin()
      ]
    },
    webpackKit.devServer(webpack, {
      host: webpackEnv.host,
      port: webpackEnv.port
    }),
    webpackKit.loadJS({
      include: PATHS.src,
      eslintOptions: {
        // Emit warnings over errors to avoid crashing
        // HMR on error.
        emitWarning: true
      }
    }),

    // Load global styles
    webpackKit.loadCSS({ include: PATHS.styles })
  ])
}
<commit_msg>Improve webpack configuratio to use lazy loading.<commit_after>'use strict'

// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development'

const path = require('path')

const { AotPlugin } = require('@ngtools/webpack')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const opener = require('opener')
const webpack = require('webpack')
const merge = require('webpack-merge')
const webpackKit = require('webpack-kit-nimedev')
const webpackEnv = require('./config/webpack-environment')

const PATHS = {
  src: path.join(__dirname, 'src'),
  dist: path.join(__dirname, 'dist'),
  images: path.join(__dirname, 'src/assets/images'),
  icons: path.join(__dirname, 'src/assets/icons'),
  fonts: path.join(__dirname, 'src/assets/fonts'),
  styles: path.join(__dirname, 'src/styles/index.css'),
  componentStyles: path.join(__dirname, 'src/app')
}

const common = merge([
  // Common settings
  {
    entry: {
      app: `${PATHS.src}/main.ts`,
      polyfills: `${PATHS.src}/polyfills.ts`
    },
    output: {
      path: PATHS.dist,
      filename: '[name].js'
    },
    resolve: {
      extensions: ['.ts', '.js', '.json', '.css']
    },

    // TypeScript loaders.
    module: {
      rules: [{
        test: /\.ts$/,
        include: PATHS.src,
        enforce: 'pre',

        use: 'tslint-loader'
      }, {
        test: /\.ts$/,
        include: PATHS.src,

        use: '@ngtools/webpack'
      }]
    },

    plugins: [
      new webpack.DefinePlugin(Object.assign(
        {},
        webpackEnv.defineEnvironment
      )),
      new AotPlugin({
        entryModule: `${PATHS.src}/app/app.module#AppModule`,
        tsConfigPath: `${PATHS.src}/tsconfig.aot.json`
      })
    ]
  },
  webpackKit.loadHtml({ include: PATHS.src }),
  webpackKit.loadImages({
    include: PATHS.images,
    options: {
      name: './assets/images/[name].[hash].[ext]',
      limit: 25000
    }
  }),
  webpackKit.loadSvgSprite({
    include: PATHS.icons,
    options: {
      name: './assets/icons/[name].[hash].[ext]'
    }
  }),
  webpackKit.loadFonts({ include: PATHS.fonts }),
  webpackKit.loadAssets({ include: PATHS.src }),

  // CSS
  webpackKit.lintCSS({ files: 'src/**/*.css' }),

  // Load css of components
  webpackKit.loadCSS({
    include: PATHS.componentStyles,
    useExportsLoader: true
  }),

  // JS
  webpackKit.loadJS({
    include: PATHS.src,
    eslintOptions: {
      // Emit warnings over errors to avoid crashing
      // HMR on error.
      emitWarning: process.env.NODE_ENV === 'development'
    }
  }),

  // Plugins
  webpackKit.htmlPlugin({ template: './src/index.html' }, ['polyfills', 'vendor', 'app'])
])

module.exports = ({ target }) => {
  // Return production configuration
  if (target === 'production') {
    return merge([
      common,
      {
        output: {
          filename: '[name].[chunkhash].js',
          chunkFilename: '[id].[chunkhash].js'
        },
        plugins: [
          new webpack.HashedModuleIdsPlugin(),
          new CleanWebpackPlugin([PATHS.dist], {
            // Without `root` CleanWebpackPlugin won't point to our
            // project and will fail to work.
            root: process.cwd()
          }),
          new webpack.optimize.UglifyJsPlugin({
            compress: {
              warnings: false
            }
          })
        ]
      },
      webpackKit.extractVendor(webpack, { chunks: ['app'] }),

      // Load global styles
      webpackKit.extractCSS({ include: PATHS.styles })
    ])
  }

  // Run opener
  opener(`http://${webpackEnv.host}:${webpackEnv.port}`)

  // Return development configurations
  return merge([
    common,
    {
      devtool: '#inline-source-map',
      plugins: [
        new webpack.NamedModulesPlugin()
      ]
    },
    webpackKit.devServer(webpack, {
      host: webpackEnv.host,
      port: webpackEnv.port
    }),

    // Load global styles
    webpackKit.loadCSS({ include: PATHS.styles })
  ])
}
<|endoftext|>


<commit_before>var projectRoot = process.cwd()

// Overriding default base webpack config
var config = {
  entry: {
    index: './docs/index.js'
  },
  resolve: {
    // Aliases - Used for pointing to reusable parts of your app
    alias: {
      'src': projectRoot + '/src',
      'docs': projectRoot + '/src/docs',
      'images': projectRoot + '/src/docs/assets/images',
      'scss': projectRoot + '/src/docs/assets/scss',
      'slim-select': projectRoot + '/src/slim-select'
    }
  }
}

if (process.env.ENVIRONMENT === 'production') {
  config.entry.index = './slim-select/index.ts'
  config.output = {
    library: 'slim-select',
    libraryTarget: 'umd'
  }
}

module.exports = config
<commit_msg>webpack - updated to reflect docs and production dist<commit_after>var projectRoot = process.cwd()
var path = require('path')

// Overriding default base webpack config
var config = {
  entry: {
    index: './docs/index.js'
  },
  resolve: {
    // Aliases - Used for pointing to reusable parts of your app
    alias: {
      'src': projectRoot + '/src',
      'docs': projectRoot + '/src/docs',
      'images': projectRoot + '/src/docs/assets/images',
      'scss': projectRoot + '/src/docs/assets/scss',
      'slim-select': projectRoot + '/src/slim-select'
    }
  }
}

if (process.env.DOCS) {
  config.output = {
    path: path.resolve(projectRoot, 'docs'),
    filename: '[name].js',
    publicPath: '/'
  }
} else if (process.env.ENVIRONMENT === 'production') {
  config.entry.index = [
    './slim-select/index.ts',
    './slim-select/index.scss'
  ]
  config.output = {
    library: 'slim-select',
    libraryTarget: 'umd'
  }
}

module.exports = config
<|endoftext|>


<commit_before>module.exports = {
  entry: './src/index.js',
  output: {
    path: `${__dirname}/src/public`,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      { loader: 'babel-loader?cacheDirectory', test: /\.jsx?$/, exclude: 'node_modules' }
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devtool: 'source-map'
}
<commit_msg>require whatwg-fetch for cross-origin call to graphql server<commit_after>require('whatwg-fetch')

module.exports = {
  entry: ['whatwg-fetch', './src/index.js'],
  output: {
    path: `${__dirname}/src/public`,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      { loader: 'babel-loader', test: /\.jsx?$/, exclude: 'node_modules' }
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devtool: 'source-map'
}
<|endoftext|>


<commit_before>'use strict';

// Modules
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';

module.exports = function makeWebpackConfig() {
  /**
   * Config
   * Reference: http://webpack.github.io/docs/configuration.html
   * This is the object where all configuration gets set
   */
  var config = {};

  /**
   * Entry
   * Reference: http://webpack.github.io/docs/configuration.html#entry
   * Should be an empty object if it's generating a test build
   * Karma will set this when it's a test build
   */
  config.entry = isTest ? void 0 : {
    app: './src/app/app.js'
  };

  /**
   * Output
   * Reference: http://webpack.github.io/docs/configuration.html#output
   * Should be an empty object if it's generating a test build
   * Karma will handle setting it up for you when it's a test build
   */
  config.output = isTest ? {} : {
    // Absolute output directory
    path: __dirname + '/dist',

    // Output path from the view of the page
    // Uses webpack-dev-server in development
    publicPath: isProd ? '/' : 'http://localhost:8080/',

    // Filename for entry points
    // Only adds hash in build mode
    filename: isProd ? '[name].[hash].js' : '[name].bundle.js',

    // Filename for non-entry points
    // Only adds hash in build mode
    chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
  };

  /**
   * Devtool
   * Reference: http://webpack.github.io/docs/configuration.html#devtool
   * Type of sourcemap to use per build type
   */
  if (isTest) {
    config.devtool = 'inline-source-map';
  }
  else if (isProd) {
    config.devtool = 'source-map';
  }
  else {
    config.devtool = 'eval-source-map';
  }

  /**
   * Loaders
   * Reference: http://webpack.github.io/docs/configuration.html#module-loaders
   * List: http://webpack.github.io/docs/list-of-loaders.html
   * This handles most of the magic responsible for converting modules
   */

  // Initialize module
  config.module = {
    rules: [{
      // JS LOADER
      // Reference: https://github.com/babel/babel-loader
      // Transpile .js files using babel-loader
      // Compiles ES6 and ES7 into ES5 code
      test: /\.js$/,
      loader: 'babel-loader',
      exclude: /node_modules/
    }, {
      // CSS LOADER
      // Reference: https://github.com/webpack/css-loader
      // Allow loading css through js
      //
      // Reference: https://github.com/postcss/postcss-loader
      // Postprocess your css with PostCSS plugins
      test: /\.css$/,
      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files in production builds
      //
      // Reference: https://github.com/webpack/style-loader
      // Use style-loader in development.

      loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({
        fallbackLoader: 'style-loader',
        loader: [
          {loader: 'css-loader', query: {sourceMap: true}},
          {loader: 'postcss-loader'}
        ],
      })
    }, {
      // ASSET LOADER
      // Reference: https://github.com/webpack/file-loader
      // Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
      // Rename the file using the asset hash
      // Pass along the updated reference to your code
      // You can add here any file extension you want to get copied to your output
      test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
      loader: 'file-loader'
    }, {
      // HTML LOADER
      // Reference: https://github.com/webpack/raw-loader
      // Allow loading html through js
      test: /\.html$/,
      loader: 'raw-loader'
    }]
  };

  // ISTANBUL LOADER
  // https://github.com/deepsweet/istanbul-instrumenter-loader
  // Instrument JS files with istanbul-lib-instrument for subsequent code coverage reporting
  // Skips node_modules and files that end with .test
  if (isTest) {
    config.module.rules.push({
      enforce: 'pre',
      test: /\.js$/,
      exclude: [
        /node_modules/,
        /\.spec\.js$/
      ],
      loader: 'istanbul-instrumenter-loader',
      query: {
        esModules: true
      }
    })
  }

  /**
   * PostCSS
   * Reference: https://github.com/postcss/autoprefixer-core
   * Add vendor prefixes to your css
   */
   // NOTE: This is now handled in the `postcss.config.js`
   //       webpack2 has some issues, making the config file necessary

  /**
   * Plugins
   * Reference: http://webpack.github.io/docs/configuration.html#plugins
   * List: http://webpack.github.io/docs/list-of-plugins.html
   */
  config.plugins = [
    new webpack.LoaderOptionsPlugin({
      test: /\.scss$/i,
      options: {
        postcss: {
          plugins: [autoprefixer]
        }
      }
    })
  ];

  // Skip rendering index.html in test mode
  if (!isTest) {
    // Reference: https://github.com/ampedandwired/html-webpack-plugin
    // Render index.html
    config.plugins.push(
      new HtmlWebpackPlugin({
        template: './src/public/index.html',
        inject: 'body'
      }),

      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files
      // Disabled when in test mode or not in build mode
      new ExtractTextPlugin({filename: 'css/[name].css', disable: !isProd, allChunks: true})
    )
  }

  // Add build specific plugins
  if (isProd) {
    config.plugins.push(
      // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
      // Only emit files when there are no errors
      new webpack.NoErrorsPlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
      // Dedupe modules in the output
      new webpack.optimize.DedupePlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
      // Minify all javascript, switch loaders to minimizing mode
      new webpack.optimize.UglifyJsPlugin(),

      // Copy assets from the public folder
      // Reference: https://github.com/kevlened/copy-webpack-plugin
      new CopyWebpackPlugin([{
        from: __dirname + '/src/public'
      }])
    )
  }

  /**
   * Dev server configuration
   * Reference: http://webpack.github.io/docs/configuration.html#devserver
   * Reference: http://webpack.github.io/docs/webpack-dev-server.html
   */
  config.devServer = {
    contentBase: './src/public',
    stats: 'minimal'
  };

  return config;
}();
<commit_msg>fix typo in comment, fixes #75<commit_after>'use strict';

// Modules
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';

module.exports = function makeWebpackConfig() {
  /**
   * Config
   * Reference: http://webpack.github.io/docs/configuration.html
   * This is the object where all configuration gets set
   */
  var config = {};

  /**
   * Entry
   * Reference: http://webpack.github.io/docs/configuration.html#entry
   * Should be an empty object if it's generating a test build
   * Karma will set this when it's a test build
   */
  config.entry = isTest ? void 0 : {
    app: './src/app/app.js'
  };

  /**
   * Output
   * Reference: http://webpack.github.io/docs/configuration.html#output
   * Should be an empty object if it's generating a test build
   * Karma will handle setting it up for you when it's a test build
   */
  config.output = isTest ? {} : {
    // Absolute output directory
    path: __dirname + '/dist',

    // Output path from the view of the page
    // Uses webpack-dev-server in development
    publicPath: isProd ? '/' : 'http://localhost:8080/',

    // Filename for entry points
    // Only adds hash in build mode
    filename: isProd ? '[name].[hash].js' : '[name].bundle.js',

    // Filename for non-entry points
    // Only adds hash in build mode
    chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
  };

  /**
   * Devtool
   * Reference: http://webpack.github.io/docs/configuration.html#devtool
   * Type of sourcemap to use per build type
   */
  if (isTest) {
    config.devtool = 'inline-source-map';
  }
  else if (isProd) {
    config.devtool = 'source-map';
  }
  else {
    config.devtool = 'eval-source-map';
  }

  /**
   * Loaders
   * Reference: http://webpack.github.io/docs/configuration.html#module-loaders
   * List: http://webpack.github.io/docs/list-of-loaders.html
   * This handles most of the magic responsible for converting modules
   */

  // Initialize module
  config.module = {
    rules: [{
      // JS LOADER
      // Reference: https://github.com/babel/babel-loader
      // Transpile .js files using babel-loader
      // Compiles ES6 and ES7 into ES5 code
      test: /\.js$/,
      loader: 'babel-loader',
      exclude: /node_modules/
    }, {
      // CSS LOADER
      // Reference: https://github.com/webpack/css-loader
      // Allow loading css through js
      //
      // Reference: https://github.com/postcss/postcss-loader
      // Postprocess your css with PostCSS plugins
      test: /\.css$/,
      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files in production builds
      //
      // Reference: https://github.com/webpack/style-loader
      // Use style-loader in development.

      loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({
        fallbackLoader: 'style-loader',
        loader: [
          {loader: 'css-loader', query: {sourceMap: true}},
          {loader: 'postcss-loader'}
        ],
      })
    }, {
      // ASSET LOADER
      // Reference: https://github.com/webpack/file-loader
      // Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
      // Rename the file using the asset hash
      // Pass along the updated reference to your code
      // You can add here any file extension you want to get copied to your output
      test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
      loader: 'file-loader'
    }, {
      // HTML LOADER
      // Reference: https://github.com/webpack/raw-loader
      // Allow loading html through js
      test: /\.html$/,
      loader: 'raw-loader'
    }]
  };

  // ISTANBUL LOADER
  // https://github.com/deepsweet/istanbul-instrumenter-loader
  // Instrument JS files with istanbul-lib-instrument for subsequent code coverage reporting
  // Skips node_modules and files that end with .spec.js
  if (isTest) {
    config.module.rules.push({
      enforce: 'pre',
      test: /\.js$/,
      exclude: [
        /node_modules/,
        /\.spec\.js$/
      ],
      loader: 'istanbul-instrumenter-loader',
      query: {
        esModules: true
      }
    })
  }

  /**
   * PostCSS
   * Reference: https://github.com/postcss/autoprefixer-core
   * Add vendor prefixes to your css
   */
   // NOTE: This is now handled in the `postcss.config.js`
   //       webpack2 has some issues, making the config file necessary

  /**
   * Plugins
   * Reference: http://webpack.github.io/docs/configuration.html#plugins
   * List: http://webpack.github.io/docs/list-of-plugins.html
   */
  config.plugins = [
    new webpack.LoaderOptionsPlugin({
      test: /\.scss$/i,
      options: {
        postcss: {
          plugins: [autoprefixer]
        }
      }
    })
  ];

  // Skip rendering index.html in test mode
  if (!isTest) {
    // Reference: https://github.com/ampedandwired/html-webpack-plugin
    // Render index.html
    config.plugins.push(
      new HtmlWebpackPlugin({
        template: './src/public/index.html',
        inject: 'body'
      }),

      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files
      // Disabled when in test mode or not in build mode
      new ExtractTextPlugin({filename: 'css/[name].css', disable: !isProd, allChunks: true})
    )
  }

  // Add build specific plugins
  if (isProd) {
    config.plugins.push(
      // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
      // Only emit files when there are no errors
      new webpack.NoErrorsPlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
      // Dedupe modules in the output
      new webpack.optimize.DedupePlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
      // Minify all javascript, switch loaders to minimizing mode
      new webpack.optimize.UglifyJsPlugin(),

      // Copy assets from the public folder
      // Reference: https://github.com/kevlened/copy-webpack-plugin
      new CopyWebpackPlugin([{
        from: __dirname + '/src/public'
      }])
    )
  }

  /**
   * Dev server configuration
   * Reference: http://webpack.github.io/docs/configuration.html#devserver
   * Reference: http://webpack.github.io/docs/webpack-dev-server.html
   */
  config.devServer = {
    contentBase: './src/public',
    stats: 'minimal'
  };

  return config;
}();
<|endoftext|>


<commit_before>const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

// /////////////////////////////////////
// Defaults
// /////////////////////////////////////

const defaults = {
	mode: "development",
	context: __dirname,
	entry: {
		Tone: "./Tone/index.ts",
	},
	output: {
		path: path.resolve(__dirname, "build"),
		filename: "[name].js",
		library: "Tone",
		libraryTarget: "umd"
	},
	resolve: {
		extensions: [".ts", ".js"]
	},
	module: {
		rules: [
			{
				test: /\.ts$/,
				use: "ts-loader",
				exclude: /(node_modules)/,
			}
		]
	},
	devtool: "cheap-source-map",
};

// /////////////////////////////////////
// Scratch
// /////////////////////////////////////

const scratch = Object.assign({}, defaults, {
	entry: {
		scratch: "./examples/scratch.ts",
	},
	plugins: [
		new HtmlWebpackPlugin({
			template: "./examples/scratch.html"
		})
	],
});

// /////////////////////////////////////
// Tests
// /////////////////////////////////////

const test = Object.assign({}, defaults, {
	entry: {
		test: "./test/test.js",
	},
	plugins: [
		new HtmlWebpackPlugin({
			filename: "test.html",
			template: "./test/index.html",
		})
	],
});

// /////////////////////////////////////
// Production
// /////////////////////////////////////

const production = Object.assign({}, defaults, {
	mode: "production",
	devtool: "source-map",
});

module.exports = env => {
	if (env.test) {
		return test;
	} else if (env.production) {
		return production;
	} else {
		return scratch;
	}
};
<commit_msg>adding globalObject<commit_after>/* eslint-disable @typescript-eslint/no-var-requires */
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

// /////////////////////////////////////
// Defaults
// /////////////////////////////////////

const defaults = {
	mode: "development",
	context: __dirname,
	entry: {
		Tone: "./Tone/index.ts",
	},
	output: {
		path: path.resolve(__dirname, "build"),
		filename: "[name].js",
		library: "Tone",
		libraryTarget: "umd",
		globalObject: "typeof self !== 'undefined' ? self : this",
	},
	resolve: {
		extensions: [".ts", ".js"]
	},
	module: {
		rules: [
			{
				test: /\.ts$/,
				use: "ts-loader",
				exclude: /(node_modules)/,
			}
		]
	},
	devtool: "cheap-source-map",
};

// /////////////////////////////////////
// Scratch
// /////////////////////////////////////

const scratch = Object.assign({}, defaults, {
	entry: {
		scratch: "./examples/scratch.ts",
	},
	plugins: [
		new HtmlWebpackPlugin({
			template: "./examples/scratch.html"
		})
	],
});

// /////////////////////////////////////
// Tests
// /////////////////////////////////////

const test = Object.assign({}, defaults, {
	entry: {
		test: "./test/test.js",
	},
	plugins: [
		new HtmlWebpackPlugin({
			filename: "test.html",
			template: "./test/index.html",
		})
	],
});

// /////////////////////////////////////
// Production
// /////////////////////////////////////

const production = Object.assign({}, defaults, {
	mode: "production",
	devtool: "source-map",
});

module.exports = env => {
	if (env.test) {
		return test;
	} else if (env.production) {
		return production;
	} else {
		return scratch;
	}
};
<|endoftext|>


<commit_before>//var BowerWebpackPlugin = require("bower-webpack-plugin");
var webpack = require("webpack");
module.exports = {
  cache: true,
  entry: './js/main.js',
  output: {
    path: __dirname,
    filename: './js/build/bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {
          cacheDirectory: true,
          presets: ['es2015']
        }
      },
      { test: /\.css$/, loader: "style-loader!css-loader" },
      /*
      下のものは、url-loaderでやると１ファイルにまとまっていいが、
      font-awesomeが特別な種類のフォントを使っている問題でまとめられないからfile-loaderでやっている
      */
      { test: /\.(ttf|eot|svg|woff2|woff)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file?name=js/build/[path][name].[ext]" }
    ]
  },
  resolve: {
    modulesDirectories: ["web_modules", "node_modules", "bower_components"],
    alias: {
      "font-awesome": "font-awesome/css/font-awesome.css"
    }
  },
  plugins: [new webpack.ResolverPlugin(
    new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
  )]
};
<commit_msg>ダブルクォーテーションに修正<commit_after>//var BowerWebpackPlugin = require("bower-webpack-plugin");
var webpack = require("webpack");
module.exports = {
  cache: true,
  entry: "./js/main.js",
  output: {
    path: __dirname,
    filename: "./js/build/bundle.js"
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: "babel",
        query: {
          cacheDirectory: true,
          presets: ["es2015"]
        }
      },
      { test: /\.css$/, loader: "style-loader!css-loader" },
      /*
      下のものは、url-loaderでやると１ファイルにまとまっていいが、
      font-awesomeが特別な種類のフォントを使っている問題でまとめられないからfile-loaderでやっている
      */
      { test: /\.(ttf|eot|svg|woff2|woff)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file?name=js/build/[path][name].[ext]" }
    ]
  },
  resolve: {
    modulesDirectories: ["web_modules", "node_modules", "bower_components"],
    alias: {
      "font-awesome": "font-awesome/css/font-awesome.css"
    }
  },
  plugins: [new webpack.ResolverPlugin(
    new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
  )]
};
<|endoftext|>


<commit_before>const webpack = require("webpack");
const path = require("path");
const merge = require("webpack-merge");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const glob = require("glob");

const parts = require("./webpack.parts");

const PATHS = {
  app: path.join(__dirname, "src"),
  build: path.join(__dirname, "dist"),
};

const commonConfig = merge([
  {
    output: {
      // Needed for code splitting to work in nested paths
      publicPath: "/",
    },
    resolveLoader: {
      alias: {
        "demo-loader": path.resolve(
          __dirname,
          "loaders/demo-loader.js"
        ),
      },
    },
  },
  parts.loadJavaScript({ include: PATHS.app }),
  parts.setFreeVariable("HELLO", "hello from config"),
]);

const productionConfig = merge([
  {
    performance: {
      hints: "warning", // "error" or false are valid too
      maxEntrypointSize: 150000, // in bytes, default 250k
      maxAssetSize: 450000, // in bytes
    },
  },
  {
    recordsPath: path.join(__dirname, "records.json"),
    output: {
      chunkFilename: "[name].[chunkhash:4].js",
      filename: "[name].[chunkhash:4].js",
    },
  },
  parts.clean(PATHS.build),
  parts.minifyJavaScript(),
  parts.minifyCSS({
    options: {
      discardComments: {
        removeAll: true,
      },
      // Run cssnano in safe mode to avoid
      // potentially unsafe transformations.
      safe: true,
    },
  }),
  parts.extractCSS({
    use: ["css-loader", parts.autoprefix()],
  }),
  parts.purifyCSS({
    paths: glob.sync(`${PATHS.app}/**/*.js`, { nodir: true }),
  }),
  parts.loadImages({
    options: {
      limit: 15000,
      name: "[name].[hash:4].[ext]",
    },
  }),
  parts.generateSourceMaps({ type: "source-map" }),
  {
    optimization: {
      splitChunks: {
        chunks: "initial",
      },
      runtimeChunk: {
        name: "manifest",
      },
    },
  },
  parts.attachRevision(),
]);

const developmentConfig = merge([
  parts.devServer({
    // Customize host/port here if needed
    host: process.env.HOST,
    port: process.env.PORT,
  }),
  parts.loadCSS(),
  parts.loadImages(),
]);

module.exports = mode => {
  const pages = [
    parts.page({
      title: "Webpack demo",
      entry: {
        app: PATHS.app,
      },
      chunks: ["app", "manifest", "vendor"],
    }),
    parts.page({
      title: "Another demo",
      path: "another",
      entry: {
        another: path.join(PATHS.app, "another.js"),
      },
      chunks: ["another", "manifest", "vendor"],
    }),
  ];
  const config =
    mode === "production" ? productionConfig : developmentConfig;

  return merge([commonConfig, config, { mode }].concat(pages));
};
<commit_msg>chore: Drop unused imports<commit_after>const path = require("path");
const merge = require("webpack-merge");
const glob = require("glob");

const parts = require("./webpack.parts");

const PATHS = {
  app: path.join(__dirname, "src"),
  build: path.join(__dirname, "dist"),
};

const commonConfig = merge([
  {
    output: {
      // Needed for code splitting to work in nested paths
      publicPath: "/",
    },
    resolveLoader: {
      alias: {
        "demo-loader": path.resolve(
          __dirname,
          "loaders/demo-loader.js"
        ),
      },
    },
  },
  parts.loadJavaScript({ include: PATHS.app }),
  parts.setFreeVariable("HELLO", "hello from config"),
]);

const productionConfig = merge([
  {
    performance: {
      hints: "warning", // "error" or false are valid too
      maxEntrypointSize: 150000, // in bytes, default 250k
      maxAssetSize: 450000, // in bytes
    },
  },
  {
    recordsPath: path.join(__dirname, "records.json"),
    output: {
      chunkFilename: "[name].[chunkhash:4].js",
      filename: "[name].[chunkhash:4].js",
    },
  },
  parts.clean(PATHS.build),
  parts.minifyJavaScript(),
  parts.minifyCSS({
    options: {
      discardComments: {
        removeAll: true,
      },
      // Run cssnano in safe mode to avoid
      // potentially unsafe transformations.
      safe: true,
    },
  }),
  parts.extractCSS({
    use: ["css-loader", parts.autoprefix()],
  }),
  parts.purifyCSS({
    paths: glob.sync(`${PATHS.app}/**/*.js`, { nodir: true }),
  }),
  parts.loadImages({
    options: {
      limit: 15000,
      name: "[name].[hash:4].[ext]",
    },
  }),
  parts.generateSourceMaps({ type: "source-map" }),
  {
    optimization: {
      splitChunks: {
        chunks: "initial",
      },
      runtimeChunk: {
        name: "manifest",
      },
    },
  },
  parts.attachRevision(),
]);

const developmentConfig = merge([
  parts.devServer({
    // Customize host/port here if needed
    host: process.env.HOST,
    port: process.env.PORT,
  }),
  parts.loadCSS(),
  parts.loadImages(),
]);

module.exports = mode => {
  const pages = [
    parts.page({
      title: "Webpack demo",
      entry: {
        app: PATHS.app,
      },
      chunks: ["app", "manifest", "vendor"],
    }),
    parts.page({
      title: "Another demo",
      path: "another",
      entry: {
        another: path.join(PATHS.app, "another.js"),
      },
      chunks: ["another", "manifest", "vendor"],
    }),
  ];
  const config =
    mode === "production" ? productionConfig : developmentConfig;

  return merge([commonConfig, config, { mode }].concat(pages));
};
<|endoftext|>


<commit_before>var path = require("path");
var srcPath = path.resolve(__dirname, "./public/assets/zdr");
var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: {
        index: path.resolve(srcPath, "./index"),
        error_404: path.resolve(srcPath, "./common/error_404")
    },
    output: {
        path: path.resolve(srcPath, "./build"),
        filename: "[name].bundle.js",
        chunkFilename: "[id].bundle.js",
    },
    resolve: {
        extensions: ["", ".js", ".jsx"],
        alias: {
            common: path.resolve(srcPath, "./common"),
            bootstrap: path.resolve(srcPath, "../libs/bootstrap")
        }
    },
    externals: {
        "react": "React",
        "jquery": "jQuery",
        "lodash": "_",
        "moment": "moment",
        "mousetrap": "Mousetrap"
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loader: "jsx?harmony"
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract("style", "css")
            },
            {
                test: /\.less$/,
                loader: ExtractTextPlugin.extract("style", "css!less")
            },
            {
                test: /\.(png|jpg)$/,
                loader: "url?limit=8192"
            },
            {
                test: /\.woff$/,
                loader: "url?limit=100000&mimetype=application/font-woff"
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin("[name].bundle.css")
    ]
};
<commit_msg>remove jsx-loader & add babel<commit_after>var path = require("path");
var srcPath = path.resolve(__dirname, "./public/assets/zdr");
var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: {
        index: path.resolve(srcPath, "./index"),
        error_404: path.resolve(srcPath, "./common/error_404")
    },
    output: {
        path: path.resolve(srcPath, "./build"),
        filename: "[name].bundle.js",
        chunkFilename: "[id].bundle.js",
    },
    resolve: {
        extensions: ["", ".js", ".jsx"],
        alias: {
            common: path.resolve(srcPath, "./common"),
            bootstrap: path.resolve(srcPath, "../libs/bootstrap")
        }
    },
    externals: {
        "react": "React",
        "jquery": "jQuery",
        "lodash": "_",
        "moment": "moment",
        "mousetrap": "Mousetrap"
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: "babel-loader"
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                loader: ExtractTextPlugin.extract("style", "css")
            },
            {
                test: /\.less$/,
                exclude: /node_modules/,
                loader: ExtractTextPlugin.extract("style", "css!less")
            },
            {
                test: /\.(png|jpg)$/,
                exclude: /node_modules/,
                loader: "url?limit=8192"
            },
            {
                test: /\.woff$/,
                exclude: /node_modules/,
                loader: "url?limit=100000&mimetype=application/font-woff"
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin("[name].bundle.css")
    ]
};
<|endoftext|>