<commit_before>"use strict";
const webpack = require('webpack');
const path = require('path');
const loadersConf = require('./webpack.loaders');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const DashboardPlugin = require('webpack-dashboard/plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const HOST = process.env.HOST || "127.0.0.1";
const PORT = process.env.PORT || "8888";

module.exports = {
  entry: [
    // POLYFILL: Set up an ES6-ish environment
    // Either the entire babel-polyfill
    // Or fine-tune es6 features needed (included into babel-polyfill)
    // Example:
    // 'babel-polyfill',  // The entire babel-polyfill
    'core-js/fn/promise',
    'core-js/es6/object',
    'core-js/es6/array',

    'react-hot-loader/patch',
    './src/index.jsx', // your app's entry point
  ],
  devtool: process.env.WEBPACK_DEVTOOL || 'eval-source-map',
  output: {
    publicPath: '/',
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  },
  module: {
    rules: loadersConf
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    modules: [
      path.join(__dirname, "src"),
      path.join(__dirname, "node_modules"), // the old 'fallback' option (needed for npm link-ed packages)
    ],
    alias: {
      "styles": path.resolve(__dirname, 'styles/'),
    }
  },
  devServer: {
    contentBase: "./public",
    // do not print bundle build stats
    noInfo: true,
    // enable HMR
    hot: true,
    // embed the webpack-dev-server runtime into the bundle
    inline: true,
    // serve index.html in place of 404 responses to allow HTML5 history
    historyApiFallback: true,
    port: PORT,
    host: HOST
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new ExtractTextPlugin({
      filename: 'style.css',
      allChunks: true
    }),
    new DashboardPlugin(),
    new HtmlWebpackPlugin({
      template: './src/template.html',
      files: {
        css: ['style.css'],
        js: [ "bundle.js"],
      }
    }),
  ]
};
<commit_msg>Comments<commit_after>"use strict";
const webpack = require('webpack');
const path = require('path');
const loadersConf = require('./webpack.loaders');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const DashboardPlugin = require('webpack-dashboard/plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const HOST = process.env.HOST || "127.0.0.1";
const PORT = process.env.PORT || "8888";

module.exports = {
  entry: [
    // POLYFILL: Set up an ES6-ish environment
    // 'babel-polyfill',  // The entire babel-polyfill
    // Or pick es6 features needed (included into babel-polyfill)
    'core-js/fn/promise',
    'core-js/es6/object',
    'core-js/es6/array',

    'react-hot-loader/patch',
    './src/index.jsx', // your app's entry point
  ],
  devtool: process.env.WEBPACK_DEVTOOL || 'eval-source-map',
  output: {
    publicPath: '/',
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  },
  module: {
    rules: loadersConf
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    modules: [
      path.join(__dirname, "src"),
      path.join(__dirname, "node_modules"), // the old 'fallback' option (needed for npm link-ed packages)
    ],
    alias: {
      "styles": path.resolve(__dirname, 'styles/'),
    }
  },
  devServer: {
    contentBase: "./public",
    // do not print bundle build stats
    noInfo: true,
    // enable HMR
    hot: true,
    // embed the webpack-dev-server runtime into the bundle
    inline: true,
    // serve index.html in place of 404 responses to allow HTML5 history
    historyApiFallback: true,
    port: PORT,
    host: HOST
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new ExtractTextPlugin({
      filename: 'style.css',
      allChunks: true
    }),
    new DashboardPlugin(),
    new HtmlWebpackPlugin({
      template: './src/template.html',
      files: {
        css: ['style.css'],
        js: [ "bundle.js"],
      }
    }),
  ]
};
<|endoftext|>


<commit_before>/* global __dirname */
import path from 'path';
import { DefinePlugin, NamedModulesPlugin, optimize } from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import WebpackPwaManifest from 'webpack-pwa-manifest';
import OptimizeCssAssetsPlugin from 'optimize-css-assets-webpack-plugin';
import BabiliPlugin from 'babili-webpack-plugin';

const { UglifyJsPlugin } = optimize;

export default ({ production, coverage, outputPath, appConfig } = {}) => {

    const ASSET_NAME_TEMPLATE = '[name]-[hash:6].[ext]';

    const extractCss = new ExtractTextPlugin({
        filename: ASSET_NAME_TEMPLATE.replace('[ext]', 'css'),
    });

    const babelConfig = {
        compact: false,
        plugins: [],
    };

    // when running a coverage build we want to add the istanbul transform to add in instrumentation

    if (coverage) {
        babelConfig.plugins.push(['istanbul', { exclude: ['node_modules'] }]);
    }

    const rules = [
        {
            // js pipeline
            test: /\.js$/,
            exclude: /(node_modules)/,
            use: {
                loader: 'babel-loader',
                options: babelConfig,
            },
        },
        {
            // css pipeline
            test: /\.css$/,
            use: extractCss.extract({
                use: [
                    'css-loader?modules&localIdentName=[hash:base64:5]',
                ],
            }),
        },
        {
            // other assets
            test: /\.(jpe?g|png|gif|svg|eot|ttf|woff|woff2)$/,
            use: `file-loader?name=${ASSET_NAME_TEMPLATE}`,
        },
    ];

    const pwaManifest = new WebpackPwaManifest({
        name: 'Ultra rare youtube app',
        short_name: 'PreactTube',
        description: 'The rarest of youtube apps',
        background_color: '#eee',
        theme_color: '#673ab8',
        display: 'standalone',
        start_url: '/',
        icons: [{
            src: path.resolve('meta/icon.png'),
            sizes: [96, 128, 192, 256, 384, 512],
        }],

        inject: false,
    });

    const plugins = [

        new DefinePlugin({
            YOUTUBE_API_KEY: JSON.stringify(appConfig.youtubeKey),
        }),

        pwaManifest,

        new HtmlWebpackPlugin({
            template: './index.ejs',
            inject: false,
            minify: { collapseWhitespace: true },
            manifest: pwaManifest.options,
        }),

        extractCss,
    ];

    if (production) {
        plugins.push(
            new DefinePlugin({
                'process.env': {
                    NODE_ENV: 'production',
                },
            }),
            new UglifyJsPlugin({ sourceMap: true }),
            new BabiliPlugin(),
            new OptimizeCssAssetsPlugin(),
        );
    } else {
        plugins.push(new NamedModulesPlugin());
    }

    return {
        context: path.resolve(__dirname, 'src'),

        entry: './index.js',

        module: {
            rules,
        },

        plugins,

        output: {
            publicPath: '/',
            path: outputPath ? path.resolve(outputPath) : undefined,
            filename: ASSET_NAME_TEMPLATE.replace('[ext]', 'js'),
            chunkFilename: '[name]-[chunkhash].js',
        },

        resolve: {
            modules: ['node_modules'],
        },

        devtool: 'source-map',
    };
};
<commit_msg>ensure index html boolean attributes are kept collapsed<commit_after>/* global __dirname */
import path from 'path';
import { DefinePlugin, NamedModulesPlugin, optimize } from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import WebpackPwaManifest from 'webpack-pwa-manifest';
import OptimizeCssAssetsPlugin from 'optimize-css-assets-webpack-plugin';
import BabiliPlugin from 'babili-webpack-plugin';

const { UglifyJsPlugin } = optimize;

export default ({ production, coverage, outputPath, appConfig } = {}) => {

    const ASSET_NAME_TEMPLATE = '[name]-[hash:6].[ext]';

    const extractCss = new ExtractTextPlugin({
        filename: ASSET_NAME_TEMPLATE.replace('[ext]', 'css'),
    });

    const babelConfig = {
        compact: false,
        plugins: [],
    };

    // when running a coverage build we want to add the istanbul transform to add in instrumentation

    if (coverage) {
        babelConfig.plugins.push(['istanbul', { exclude: ['node_modules'] }]);
    }

    const rules = [
        {
            // js pipeline
            test: /\.js$/,
            exclude: /(node_modules)/,
            use: {
                loader: 'babel-loader',
                options: babelConfig,
            },
        },
        {
            // css pipeline
            test: /\.css$/,
            use: extractCss.extract({
                use: [
                    'css-loader?modules&localIdentName=[hash:base64:5]',
                ],
            }),
        },
        {
            // other assets
            test: /\.(jpe?g|png|gif|svg|eot|ttf|woff|woff2)$/,
            use: `file-loader?name=${ASSET_NAME_TEMPLATE}`,
        },
    ];

    const pwaManifest = new WebpackPwaManifest({
        name: 'Ultra rare youtube app',
        short_name: 'PreactTube',
        description: 'The rarest of youtube apps',
        background_color: '#eee',
        theme_color: '#673ab8',
        display: 'standalone',
        start_url: '/',
        icons: [{
            src: path.resolve('meta/icon.png'),
            sizes: [96, 128, 192, 256, 384, 512],
        }],

        inject: false,
    });

    const plugins = [

        new DefinePlugin({
            YOUTUBE_API_KEY: JSON.stringify(appConfig.youtubeKey),
        }),

        pwaManifest,

        new HtmlWebpackPlugin({
            template: './index.ejs',
            inject: false,
            minify: { collapseWhitespace: true, collapseBooleanAttributes: true },
            manifest: pwaManifest.options,
        }),

        extractCss,
    ];

    if (production) {
        plugins.push(
            new DefinePlugin({
                'process.env': {
                    NODE_ENV: 'production',
                },
            }),
            new UglifyJsPlugin({ sourceMap: true }),
            new BabiliPlugin(),
            new OptimizeCssAssetsPlugin(),
        );
    } else {
        plugins.push(new NamedModulesPlugin());
    }

    return {
        context: path.resolve(__dirname, 'src'),

        entry: './index.js',

        module: {
            rules,
        },

        plugins,

        output: {
            publicPath: '/',
            path: outputPath ? path.resolve(outputPath) : undefined,
            filename: ASSET_NAME_TEMPLATE.replace('[ext]', 'js'),
            chunkFilename: '[name]-[chunkhash].js',
        },

        resolve: {
            modules: ['node_modules'],
        },

        devtool: 'source-map',
    };
};
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var config = {
    entry: path.resolve(__dirname, 'app/src/main.js'),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: "bundle.js"
    },

    module: {
        loaders: [{
            test: /\.json$/,
            loader: "json"
        }, {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel'
        }, {
            test: /\.less$/,
            loader: 'style!css?modules&localIdentName=[name]_[local]!postcss!less'
        }, {
            test: /\.(png|jpg|gif|svg)$/,
            loader: "url?limit=8192"
        }]
    },

    postcss: [
        require('autoprefixer')
    ],

    devtool: 'eval-source-map',

    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, "app/index.html")
        })
    ],

    devServer: {
        colors: true,
        historyApiFallback: true,
        inline: true
    }
};

module.exports = config;
<commit_msg>Config for building production version.<commit_after>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const isBuild = Boolean(process.env.build);

var config = {
    entry: path.resolve(__dirname, 'app/src/main.js'),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: "bundle.js"
    },

    module: {
        loaders: [{
            test: /\.json$/,
            loader: "json"
        }, {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel'
        }, {
            test: /\.less$/,
            loader: 'style!css?modules&localIdentName=[name]_[local]!postcss!less'
        }, {
            test: /\.(png|jpg|gif|svg)$/,
            loader: "url?limit=8192"
        }]
    },

    postcss: [
        require('autoprefixer')
    ],

    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, "app/index.html")
        })
    ],

    devServer: {
        colors: true,
        historyApiFallback: true,
        inline: true
    }
};

if (isBuild) {
    config.devtool = 'source-map';
} else {
    config.devtool = 'eval-source-map';
}

module.exports = config;
<|endoftext|>


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

// builtin node path module
const path = require('path');

// It moves every require('style.css') in entry chunks into a separate css output file.
const ExtractTextPlugin = require('extract-text-webpack-plugin');
// Create html files from the bundle
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const nodeExternals = require('webpack-node-externals');

module.exports = ({ base }) => {
    const nodeEnv = process.env.NODE_ENV || 'development';
    const isProd = nodeEnv === 'production';
    const isClient = base === 'client' ? true : false

    return {
        devtool: isProd ? false : 'eval-source-map',
        mode: isProd ? 'production' : 'development',
        externals: isClient ? [] : [nodeExternals()],

        entry: isClient
            ? { index: path.join(__dirname, './app/index.jsx'), vendor: ['react', 'react-dom'] }
            : { server: path.join(__dirname, 'server.js') },

        output: {
            path: path.join(__dirname, './build'),
            filename: '[name].js',
            publicPath: '/'
        },

        optimization: {
            splitChunks: {
                chunks: 'all'
//                name: 'vendor',
//                minChunks: Infinity,
//                filename: 'vendor.bundle.js'
            },
            removeEmptyChunks: true,
            minimizer: [
                new UglifyJsPlugin({
                    parallel: true,
                    sourceMap: !isProd
                })
            ]
        },

        resolve: {
            alias: {
                '~': path.join(__dirname, './app')
            },
            extensions: ['.js', '.jsx']
        },

        target: isClient ? 'web' : 'node',

        module: {
            rules: [{
                test: /\.jsx?$/,
                loader: 'babel-loader',
                options: {
                    presets: [
                        "@babel/preset-env",
                        "@babel/preset-react",
                    ],
                    plugins: [
                        "@babel/plugin-syntax-dynamic-import"
                    ]
                }
            }, {
                test: /\.(scss|sass)$/,
                use: isClient
                    ? [
                        { loader: 'style-loader' },
                        {
                            loader: 'css-loader',
                            options:
                            {
                                modules: true
                            }
                        },
                        { loader: 'sass-loader' }
                    ]
                    : [
                        {
                            loader: 'css-loader/locals',
                            options:
                            {
                                modules: true,
                                localIdentName: '[name]--[local]--[hash:base64:5]'
                            }
                        },
                        { loader: 'sass-loader' }
                    ]
            }]
        },

        devServer: {
            historyApiFallback: true,
        },

        plugins: isClient ? [
            new webpack.DefinePlugin({
                // http://stackoverflow.com/a/35372706/2177568
                // for server side code, just require, don't chunk
                // use `if (ONSERVER) { ...` for server specific code
                ONSERVER: false,
                'process.env': { NODE_ENV: JSON.stringify(nodeEnv) }
            }),
            new FaviconsWebpackPlugin({
                logo: './app/images/favicon.png',
                prefix: 'icons-[hash]/',
                emitStats: true,
                persisentCache: true,
                background: '#000',
                inject: true
            }),
            new HtmlWebpackPlugin({
                template: 'app/index.html',
                inject: 'body',
                filename: 'index.html'
            }),
            new MiniCssExtractPlugin({
                // Options similar to the same options in webpackOptions.output
                // both options are optional
                filename: "[name].css",
                chunkFilename: "[id].css"
            })
        ] : [
            new webpack.DefinePlugin({
                // http://stackoverflow.com/a/35372706/2177568
                // for server side code, just require, don't chunk
                // use `if (ONSERVER) { ...` for server specific code
                ONSERVER: true,
                'process.env': { NODE_ENV: JSON.stringify(nodeEnv) }
            })
        ]
    }
}
<commit_msg>Fixes server side build, simplify css processing.<commit_after>const webpack = require('webpack');

// builtin node path module
const path = require('path');

// It moves every require('style.css') in entry chunks into a separate css output file.
const ExtractTextPlugin = require('extract-text-webpack-plugin');
// Create html files from the bundle
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const nodeExternals = require('webpack-node-externals');

module.exports = ({ base }) => {
    const nodeEnv = process.env.NODE_ENV || 'development';
    const isProd = nodeEnv === 'production';
    const isClient = base === 'client' ? true : false

    return {
        devtool: isProd ? false : 'eval-source-map',
        mode: isProd ? 'production' : 'development',
        externals: isClient ? [] : [nodeExternals()],

        entry: isClient
            ? { index: path.join(__dirname, './app/index.jsx'), vendor: ['react', 'react-dom'] }
            : { server: path.join(__dirname, 'server.js') },

        output: {
            path: path.join(__dirname, './build'),
            filename: '[name].js',
            publicPath: '/'
        },

        optimization: {
            splitChunks: {
                chunks: 'all'
//                name: 'vendor',
//                minChunks: Infinity,
//                filename: 'vendor.bundle.js'
            },
            removeEmptyChunks: true,
            minimizer: [
                new UglifyJsPlugin({
                    parallel: true,
                    sourceMap: !isProd
                })
            ]
        },

        resolve: {
            alias: {
                '~': path.join(__dirname, './app')
            },
            extensions: ['.js', '.jsx']
        },

        target: isClient ? 'web' : 'node',

        module: {
            rules: [{
                test: /\.jsx?$/,
                loader: 'babel-loader',
                options: {
                    presets: [
                        "@babel/preset-env",
                        "@babel/preset-react",
                    ],
                    plugins: [
                        "@babel/plugin-syntax-dynamic-import"
                    ]
                }
            }, {
                test: /\.(scss|sass)$/,
                use: [
                    { loader: 'style-loader' },
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true
                        }
                    },
                    { loader: 'sass-loader' }
                ]
            }]
        },

        devServer: {
            historyApiFallback: true,
        },

        plugins: isClient ? [
            new webpack.DefinePlugin({
                // http://stackoverflow.com/a/35372706/2177568
                // for server side code, just require, don't chunk
                // use `if (ONSERVER) { ...` for server specific code
                ONSERVER: false,
                'process.env': { NODE_ENV: JSON.stringify(nodeEnv) }
            }),
            new FaviconsWebpackPlugin({
                logo: './app/images/favicon.png',
                prefix: 'icons-[hash]/',
                emitStats: true,
                persisentCache: true,
                background: '#000',
                inject: true
            }),
            new HtmlWebpackPlugin({
                template: 'app/index.html',
                inject: 'body',
                filename: 'index.html'
            }),
            new MiniCssExtractPlugin({
                // Options similar to the same options in webpackOptions.output
                // both options are optional
                filename: "[name].css",
                chunkFilename: "[id].css"
            })
        ] : [
            new webpack.DefinePlugin({
                // http://stackoverflow.com/a/35372706/2177568
                // for server side code, just require, don't chunk
                // use `if (ONSERVER) { ...` for server specific code
                ONSERVER: true,
                'process.env': { NODE_ENV: JSON.stringify(nodeEnv) }
            })
        ]
    }
}
<|endoftext|>


<commit_before>/* global process, require, module, __dirname */

const path = require( 'path' );

const externals = {
	// Make localized data importable.
	'amp-validation-i18n': 'ampValidationI18n',
	jquery: 'jQuery',
	lodash: 'lodash',
	react: 'React',
	'react-dom': 'ReactDOM',
};

// Define WordPress dependencies
const wpDependencies = [
	'blocks',
	'components',
	'compose',
	'data',
	'editor',
	'edit-post',
	'element',
	'hooks',
	'i18n',
	'api-fetch',
	'blocks',
	'components',
	'compose',
	'date',
	'editor',
	'element',
	'hooks',
	'i18n',
	'utils',
	'data',
	'viewport',
	'core-data',
	'plugins',
	'edit-post',
	'keycodes',
];

/**
 * Given a string, returns a new string with dash separators converted to
 * camel-case equivalent. This is not as aggressive as `_.camelCase` in
 * converting to uppercase, where Lodash will convert letters following
 * numbers.
 *
 * @param {string} string Input dash-delimited string.
 *
 * @return {string} Camel-cased string.
 */
function camelCaseDash( string ) {
	return string.replace(
		/-([a-z])/,
		( match, letter ) => letter.toUpperCase()
	);
}

wpDependencies.forEach( ( name ) => {
	externals[ `@wordpress/${ name }` ] = {
		this: [ 'wp', camelCaseDash( name ) ],
	};
} );

const isProduction = process.env.NODE_ENV === 'production';

module.exports = {
	mode: isProduction ? 'production' : 'development',
	entry: {
		'./assets/js/amp-blocks-compiled': './assets/src/blocks/index.js',
		'./assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle.js',
		'./assets/js/amp-validation-detail-toggle-compiled': './assets/src/amp-validation-detail-toggle.js',
		'./assets/js/amp-validation-single-error-url-details-compiled': './assets/src/amp-validation-single-error-url-details.js',
		'./assets/js/amp-story-editor-blocks-compiled': './assets/src/amp-story-editor-blocks.js',
		'./assets/js/amp-story-blocks-compiled': './assets/src/blocks/stories.js',
	},
	output: {
		path: path.resolve( __dirname ),
		filename: '[name].js',
		library: 'AMP',
		libraryTarget: 'this',
	},
	externals,
	devtool: isProduction ? undefined : 'cheap-eval-source-map',
	module: {
		rules: [
			{
				test: /\.js$/,
				exclude: /node_modules/,
				use: {
					loader: 'babel-loader',
				},
			},
		],
	},
};
<commit_msg>Further text block improvements<commit_after>/* global process, require, module, __dirname */

const path = require( 'path' );

const externals = {
	// Make localized data importable.
	'amp-validation-i18n': 'ampValidationI18n',
	jquery: 'jQuery',
	lodash: 'lodash',
	react: 'React',
	'react-dom': 'ReactDOM',
};

// Define WordPress dependencies
const wpDependencies = [
	'blocks',
	'components',
	'compose',
	'data',
	'editor',
	'edit-post',
	'element',
	'hooks',
	'i18n',
	'api-fetch',
	'blocks',
	'components',
	'compose',
	'date',
	'editor',
	'element',
	'hooks',
	'i18n',
	'utils',
	'data',
	'viewport',
	'core-data',
	'plugins',
	'edit-post',
	'keycodes',
	'wordcount',
];

/**
 * Given a string, returns a new string with dash separators converted to
 * camel-case equivalent. This is not as aggressive as `_.camelCase` in
 * converting to uppercase, where Lodash will convert letters following
 * numbers.
 *
 * @param {string} string Input dash-delimited string.
 *
 * @return {string} Camel-cased string.
 */
function camelCaseDash( string ) {
	return string.replace(
		/-([a-z])/,
		( match, letter ) => letter.toUpperCase()
	);
}

wpDependencies.forEach( ( name ) => {
	externals[ `@wordpress/${ name }` ] = {
		this: [ 'wp', camelCaseDash( name ) ],
	};
} );

const isProduction = process.env.NODE_ENV === 'production';

module.exports = {
	mode: isProduction ? 'production' : 'development',
	entry: {
		'./assets/js/amp-blocks-compiled': './assets/src/blocks/index.js',
		'./assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle.js',
		'./assets/js/amp-validation-detail-toggle-compiled': './assets/src/amp-validation-detail-toggle.js',
		'./assets/js/amp-validation-single-error-url-details-compiled': './assets/src/amp-validation-single-error-url-details.js',
		'./assets/js/amp-story-editor-blocks-compiled': './assets/src/amp-story-editor-blocks.js',
		'./assets/js/amp-story-blocks-compiled': './assets/src/blocks/stories.js',
	},
	output: {
		path: path.resolve( __dirname ),
		filename: '[name].js',
		library: 'AMP',
		libraryTarget: 'this',
	},
	externals,
	devtool: isProduction ? undefined : 'cheap-eval-source-map',
	module: {
		rules: [
			{
				test: /\.js$/,
				exclude: /node_modules/,
				use: {
					loader: 'babel-loader',
				},
			},
		],
	},
};
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  entry: {
    app: './src/index.js',
    styles: './style/scss/styles.scss'
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    publicPath: '/dist/',
    filename: '[name].bundle.js'
  },
  module: {
    rules:[
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [{
          loader: 'babel-loader',
        }]
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'postcss-loader',
          },
          'sass-loader',
        ]
      }
    ]
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  },
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].bundle.css',
      chunkFilename: '[id].bundle.css'
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      'env.host': process.env.NODE_DEV === 'production' && '"https://tic-tac-toe-socketio.herokuapp.com"' || '"http://localhost:3050"'
    })
  ]
};

/*
,
          {
            loader: 'postcss-loader',
            options: {
              ident: 'postcss',
              plugins: (loader) => [
                require('postcss-import')({ root: loader.resourcePath }),
                require('postcss-cssnext')(),
                require('cssnano')()
              ]
            }
          }
*/<commit_msg>removed postcss loader for now<commit_after>'use strict';

const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  entry: {
    app: './src/index.js',
    styles: './style/scss/styles.scss'
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    publicPath: '/dist/',
    filename: '[name].bundle.js'
  },
  module: {
    rules:[
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [{
          loader: 'babel-loader',
        }]
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
          'sass-loader',
        ]
      }
    ]
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './',
    mode: 'development'
  },
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].bundle.css',
      chunkFilename: '[id].bundle.css'
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      'env.host': process.env.NODE_ENV === 'production' && '"https://tic-tac-toe-socketio.herokuapp.com"' || '"http://localhost:3050"'
    })
  ]
};<|endoftext|>


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

// 一句话理解 path和 publicPath的作用！！！！
// path 用来存放打包后文件的输出目录
// publicPath 用来定义静态资源的引用地址

module.exports = {
  devtool: 'inline-source-map',
  entry: {
    index: [
      'react-hot-loader/patch',
      // 开启 React 代码的模块热替换(HMR)

      'webpack-dev-server/client?http://localhost:3000',
      // 为 webpack-dev-server 的环境打包代码
      // 然后连接到指定服务器域名与端口

      'webpack/hot/only-dev-server',
      // 为热替换(HMR)打包好代码
      // only- 意味着只有成功更新运行代码才会执行热替换(HMR)

      './index.jsx',
      // 我们 app 的入口文件
    ],
    vendor: ['react', 'react-dom', 'react-redux', 'react-router-dom', 'redux', 'redux-thunk'],
  },
  output: {
    filename: '[name].js',
    // 输出的打包文件

    path: `${__dirname}/dist/assets/`,
    // 项目输出路径
    publicPath: '/assets/',
    // 对于热替换(HMR)是必须的，让 webpack 知道在哪里载入热更新的模块(chunk)
  },

  context: `${__dirname}/src`,
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: [
          'babel-loader', 'eslint-loader',
        ],
        exclude: /^node_modules$/,
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader',
        ],
        exclude: /^node_modules$/,
      },
      {
        test: /\.less$/,
        use: [
          'style-loader',
          'css-loader',
          'less-loader',
        ],
        exclude: /^node_modules$/,
      },
      {
         // 匹配.html文件
        test: /\.html$/,
        use: [
          {
            loader: 'html-loader',
            options: {
              attrs: ['img:src', 'link:href'],
            },
          },
        ],
        exclude: /^node_modules$/,
      },
      {
        test: /favicon\.png$/,
        use: [
          {
           // 使用file-loader
            loader: 'file-loader',
            options: {
              name: '[name].[ext]?[hash]',
            },
          },
        ],
        exclude: /^node_modules$/,
      },
      {
        // 处理静态资源
        test: /\.(png|jpg|jpeg|gif|eot|ttf|woff|woff2|svg|svgz)(\?.+)?$/,
        exclude: /favicon\.png$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10000,
            },
          },
        ],
      },
    ],

  },
  resolve: {
    extensions: ['.js', '.less', '.json', '.jsx'],
    alias: {
      '~': `${__dirname}/src`,
    },
  },
  plugins: [
    // 将第三方库单独打包
    new webpack.optimize.CommonsChunkPlugin({ names: ['vendor', 'manifest'] }),
    new webpack.HotModuleReplacementPlugin(),
      // 开启全局的模块热替换(HMR)
    new webpack.NamedModulesPlugin(),
    // 当模块热替换(HMR)时在浏览器控制台输出对用户更友好的模块名字信息

    new HtmlWebpackPlugin({
      template: './Template/index.html',
      filename: './index.html', // 生成的html存放路径，相对于 path
    }),
    // 生成html文件
  ],
};
<commit_msg>modified webpack.config.js<commit_after>const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

// 一句话理解 path和 publicPath的作用！！！！
// path 用来存放打包后文件的输出目录
// publicPath 用来定义静态资源的引用地址

module.exports = {
  devtool: 'inline-source-map',
  entry: {
    index: [
      'react-hot-loader/patch',
      // 开启 React 代码的模块热替换(HMR)

      'webpack-dev-server/client?http://localhost:3000',
      // 为 webpack-dev-server 的环境打包代码
      // 然后连接到指定服务器域名与端口

      'webpack/hot/only-dev-server',
      // 为热替换(HMR)打包好代码
      // only- 意味着只有成功更新运行代码才会执行热替换(HMR)

      './index.jsx',
      // 我们 app 的入口文件
    ],
    vendor: ['react', 'react-dom', 'react-redux', 'react-router-dom', 'redux', 'redux-thunk'],
  },
  output: {
    filename: '[name].js',
    // 输出的打包文件

    path: `${__dirname}/dist/assets/`,
    // 项目输出路径
    publicPath: '/assets/',
    // 对于热替换(HMR)是必须的，让 webpack 知道在哪里载入热更新的模块(chunk)
  },

  context: `${__dirname}/src`,
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: [
          'babel-loader', 'eslint-loader',
        ],
        exclude: /^node_modules$/,
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader',
        ],
        exclude: /^node_modules$/,
      },
      {
        test: /\.less$/,
        use: [
          'style-loader',
          'css-loader',
          'less-loader',
        ],
        exclude: /^node_modules$/,
      },
      {
         // 匹配.html文件
        test: /\.html$/,
        use: [
          {
            loader: 'html-loader',
            options: {
              attrs: ['img:src', 'link:href'],
            },
          },
        ],
        exclude: /^node_modules$/,
      },
      {
        test: /favicon\.png$/,
        use: [
          {
           // 使用file-loader
            loader: 'file-loader',
            options: {
              name: '[name].[ext]?[hash]',
            },
          },
        ],
        exclude: /^node_modules$/,
      },
      {
        // 处理静态资源
        test: /\.(png|jpg|jpeg|gif|eot|ttf|woff|woff2|svg|svgz)(\?.+)?$/,
        exclude: /favicon\.png$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10000,
            },
          },
        ],
      },
    ],

  },
  resolve: {
    extensions: ['.js', '.less', '.json', '.jsx'],
    alias: {
      '~': `${__dirname}/src`,
    },
  },
  plugins: [
    // 将第三方库单独打包
    new webpack.optimize.CommonsChunkPlugin({ names: ['vendor', 'manifest'] }),
    new webpack.HotModuleReplacementPlugin(),
      // 开启全局的模块热替换(HMR)
    new webpack.NamedModulesPlugin(),
    // 当模块热替换(HMR)时在浏览器控制台输出对用户更友好的模块名字信息

    new HtmlWebpackPlugin({
      template: './Template/index.html',
      filename: './index.html', // 生成的html存放路径，相对于 path
    }),
    // 生成html文件
  ],
};
<|endoftext|>


<commit_before>var path = require('path');
var debug = process.env.NODE_ENV !== "production";

module.exports = {
    context: path.join(__dirname, "client"),
    devtool: debug ? "inline-sourcemap" : null,
    entry: "./js/client.js",
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: /\.jsx?$/,
                exclude: /(node_modules|code_snippets)/,
                query: {
                    presets: ['react', 'es2015', 'stage-0'],
                    plugins: ['react-html-attrs', 'add-module-exports']
                }
            }
        ]
    },
    output: {
        filename: "./client/client.min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
    ],
}
<commit_msg>ttest<commit_after>var path = require('path');
var debug = process.env.NODE_ENV !== "production";

module.exports = {
    context: path.join(__dirname, "client"),
    devtool: debug ? "inline-sourcemap" : null,
    entry: "./js/client.js",
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                query: {
                    presets: ['react', 'es2015', 'stage-0'],
                    plugins: ['react-html-attrs', 'add-module-exports']
                }
            }
        ]
    },
    output: {
        filename: "./client/client.min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
    ],
}
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
let fs = require('fs');
var webpack = require('webpack');
const pkg = require('./package.json');
const TerserPlugin = require('terser-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

let plugins = [];

plugins.push(
    new ForkTsCheckerWebpackPlugin({
        typescript: {
            diagnosticOptions: {
                syntactic: true,
                semantic: true,
                declaration: true,
                global: true
            }
        }
    })
);

plugins.push(new webpack.BannerPlugin(
`Copyright (C) 2012-2020  Online-Go.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
`));

module.exports = (env, argv) => {
    const production = argv.mode === 'production';
    let alias = {};

    if (production) {
        console.log("Production build, enabling react profiling");
        alias = {
            'react-dom$': 'react-dom/profiling',
            'scheduler/tracing': 'scheduler/tracing-profiling',
        };
    }

    plugins.push(new webpack.EnvironmentPlugin({
        NODE_ENV: production ? 'production' : 'development',
        DEBUG: false
    }));

    let defines = {
        CLIENT: true,
        SERVER: false,
    };

    plugins.push(new webpack.DefinePlugin(defines));

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

    const config = {
        mode: production ? 'production' : 'development',
        entry: {
            'ogs': './src/main.tsx',
        },
        resolve: {
            modules: [
                'src/lib',
                'src/components',
                'src/views',
                'src',
                'node_modules'
            ],
            alias: alias,
            extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"],
        },
        output: {
            path: __dirname + '/dist',
            filename: production ? '[name].min.js' : '[name].js'
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    use: ["source-map-loader"],
                    enforce: "pre"
                },
                // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
                {
                    test: /\.tsx?$/,
                    exclude: /node_modules/,
                    use: [
                        { loader: 'cache-loader' },
                        {
                            loader: "ts-loader",
                            options: {
                                configFile: 'tsconfig.json',
                                transpileOnly: true,
                                happyPackMode: true
                            }
                        }
                    ]
                }
            ]
        },

        performance: {
            maxAssetSize: 1024 * 1024 * 2.5,
            maxEntrypointSize: 1024 * 1024 * 2.5,
        },

        optimization: {
            splitChunks: {
                cacheGroups: {
                    "vendor": {
                        test: /[\\/]node_modules[\\/]/,   // <-- use the test property to specify which deps go here
                        name: "vendor",
                        chunks: "all",
                        priority: -10
                    }
                }
            },
            minimizer: [
                new TerserPlugin({
                    terserOptions: {
                      safari10: true,
                    },
                }),
            ],
        },

        plugins: plugins,

        //devtool: production ? 'source-map' : 'eval-source-map',
        /* NOTE: The default needs to be source-map for the i18n translation stuff to work. Specifically, using eval-source-map makes it impossible for our xgettext-js parser to parse the embedded source. */
        devtool: 'source-map',

        // When importing a module whose path matches one of the following, just
        // assume a corresponding global variable exists and use that instead.
        // This is important because it allows us to avoid bundling all of our
        // dependencies, which allows browsers to cache those libraries between builds.
        externals: {
            "goban": "goban",
            "swal": "swal", // can't seem to import anyways
        },

        devServer: {
            stats: {
                assets: true,
                children: false,
                chunks: true,
                hash: true,
                modules: true,
                publicPath: true,
                timings: true,
                version: true,
                warnings: true,
            }
        },
    };

    if (!production) {
        config.optimization.removeAvailableModules = false;
        config.optimization.removeEmptyChunks = false;
        config.optimization.splitChunks = false;
    }

    return config;
};
<commit_msg>Drop safari10 terser support, we didn't work in that browser anyways apparently<commit_after>'use strict';

var path = require('path');
let fs = require('fs');
var webpack = require('webpack');
const pkg = require('./package.json');
const TerserPlugin = require('terser-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

let plugins = [];

plugins.push(
    new ForkTsCheckerWebpackPlugin({
        typescript: {
            diagnosticOptions: {
                syntactic: true,
                semantic: true,
                declaration: true,
                global: true
            }
        }
    })
);

plugins.push(new webpack.BannerPlugin(
`Copyright (C) 2012-2020  Online-Go.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
`));

module.exports = (env, argv) => {
    const production = argv.mode === 'production';
    let alias = {};

    if (production) {
        console.log("Production build, enabling react profiling");
        alias = {
            'react-dom$': 'react-dom/profiling',
            'scheduler/tracing': 'scheduler/tracing-profiling',
        };
    }

    plugins.push(new webpack.EnvironmentPlugin({
        NODE_ENV: production ? 'production' : 'development',
        DEBUG: false
    }));

    let defines = {
        CLIENT: true,
        SERVER: false,
    };

    plugins.push(new webpack.DefinePlugin(defines));

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

    const config = {
        mode: production ? 'production' : 'development',
        entry: {
            'ogs': './src/main.tsx',
        },
        resolve: {
            modules: [
                'src/lib',
                'src/components',
                'src/views',
                'src',
                'node_modules'
            ],
            alias: alias,
            extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"],
        },
        output: {
            path: __dirname + '/dist',
            filename: production ? '[name].min.js' : '[name].js'
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    use: ["source-map-loader"],
                    enforce: "pre"
                },
                // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
                {
                    test: /\.tsx?$/,
                    exclude: /node_modules/,
                    use: [
                        { loader: 'cache-loader' },
                        {
                            loader: "ts-loader",
                            options: {
                                configFile: 'tsconfig.json',
                                transpileOnly: true,
                                happyPackMode: true
                            }
                        }
                    ]
                }
            ]
        },

        performance: {
            maxAssetSize: 1024 * 1024 * 2.5,
            maxEntrypointSize: 1024 * 1024 * 2.5,
        },

        optimization: {
            splitChunks: {
                cacheGroups: {
                    "vendor": {
                        test: /[\\/]node_modules[\\/]/,   // <-- use the test property to specify which deps go here
                        name: "vendor",
                        chunks: "all",
                        priority: -10
                    }
                }
            },
            minimizer: [
                new TerserPlugin({
                    parallel: true,
                    terserOptions: {
                    },
                }),
            ],
        },

        plugins: plugins,

        //devtool: production ? 'source-map' : 'eval-source-map',
        /* NOTE: The default needs to be source-map for the i18n translation stuff to work. Specifically, using eval-source-map makes it impossible for our xgettext-js parser to parse the embedded source. */
        devtool: 'source-map',

        // When importing a module whose path matches one of the following, just
        // assume a corresponding global variable exists and use that instead.
        // This is important because it allows us to avoid bundling all of our
        // dependencies, which allows browsers to cache those libraries between builds.
        externals: {
            "goban": "goban",
            "swal": "swal", // can't seem to import anyways
        },

        devServer: {
            stats: {
                assets: true,
                children: false,
                chunks: true,
                hash: true,
                modules: true,
                publicPath: true,
                timings: true,
                version: true,
                warnings: true,
            }
        },
    };

    if (!production) {
        config.optimization.removeAvailableModules = false;
        config.optimization.removeEmptyChunks = false;
        config.optimization.splitChunks = false;
    }

    return config;
};
<|endoftext|>


<commit_before>'use strict';

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

module.exports = {
  entry: './browser/react/index.js',
  output: {
    path: path.join(__dirname, 'public'),
    publicPath: '/',
    filename: './bundle.js'
  },
  context: __dirname,
  devtool: 'source-map',
  resolve: {
    extensions: ['', '.js', '.jsx', '.scss']
  },
  // plugins: [
  //   new webpack.optimize.UglifyJsPlugin({
  //     sourceMap: false,
  //     mangle: false
  //   })
  // ],
  module: {
    loaders: [
      {
        test: /jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {
          presets: ['react', 'es2015', 'stage-2']
        }
      },
      {test: /\.scss?$/, loaders: ['style', 'css', 'sass']},
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?.*$|$)/,
        loader: 'file'
      },
      {
            // I want to uglify with mangling only app files, not thirdparty libs
            test: /.*\/App\/.*\.js$/,
            exclude: /.test.js/, // excluding .test files
            loader: "uglify"
      }
    ]
  },
  stats: {
    warnings: false
  }
};
<commit_msg>webpack<commit_after>'use strict';

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

module.exports = {
  entry: './browser/react/index.js',
  output: {
    path: path.join(__dirname, 'public'),
    publicPath: '/',
    filename: './bundle.js'
  },
  context: __dirname,
  devtool: 'source-map',
  resolve: {
    extensions: ['', '.js', '.jsx', '.scss']
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: false,
      mangle: false
    })
  ],
  module: {
    loaders: [
      {
        test: /jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {
          presets: ['react', 'es2015', 'stage-2']
        }
      },
      {test: /\.scss?$/, loaders: ['style', 'css', 'sass']},
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?.*$|$)/,
        loader: 'file'
      },
      {
            // I want to uglify with mangling only app files, not thirdparty libs
            test: /.*\/App\/.*\.js$/,
            exclude: /.test.js/, // excluding .test files
            loader: "uglify"
      }
    ]
  },
  stats: {
    warnings: false
  }
};
<|endoftext|>


<commit_before>const configBuilder = require('webpack-focus').configBuilder;
const path = require('path');
// Check if focus libraries should be held locally or read from NPM
const localFocus = process.env.LOCAL_FOCUS;
const customConfig = localFocus ? {
    resolve: {
        alias: {
            'focus-core': path.resolve(process.cwd(), '../focus-core/lib'),
            'focus-components': path.resolve(process.cwd(), '../focus-components/lib'),
            react: path.resolve(process.cwd(), './node_modules/react'),
            backbone: path.resolve(process.cwd(), './node_modules/backbone'),
            moment: path.resolve(process.cwd(), './node_modules/moment'),
            'i18next-client': path.resolve(process.cwd(), './node_modules/i18next-client')
        },
        extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx']
    }
} : {};
module.exports = configBuilder(customConfig);
<commit_msg>Fix webpack config<commit_after>const configBuilder = require('webpack-focus').configBuilder;
const path = require('path');
// Check if focus libraries should be held locally or read from NPM
const localFocus = process.env.LOCAL_FOCUS ? JSON.parse(process.env.LOCAL_FOCUS) : false;
const customConfig = localFocus ? {
    resolve: {
        alias: {
            'focus-core': path.resolve(process.cwd(), '../focus-core'),
            'focus-components': path.resolve(process.cwd(), '../focus-components'),
            react: path.resolve(process.cwd(), './node_modules/react'),
            backbone: path.resolve(process.cwd(), './node_modules/backbone'),
            moment: path.resolve(process.cwd(), './node_modules/moment'),
            'i18next-client': path.resolve(process.cwd(), './node_modules/i18next-client')
        }
    }
} : {};
module.exports = configBuilder(customConfig);
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var CleanWebpackPlugin = require('clean-webpack-plugin');
let CompressionPlugin = require("compression-webpack-plugin");//引入

const VENOR = [
"react",
"react-dom",
"react-lz-editor",
"mobx",
"mobx-react",
"react-router",
"react-router-dom",
"axios",
"bulma"
]

module.exports = {
  devtool: 'eval',
  entry: {
      // 'app':[
      //       'react-hot-loader/patch',
      //       'webpack-dev-server/client?http://localhost:3001',
      //       'webpack/hot/only-dev-server',
      //       './App/index',
      //   ],
        'admin':[
            'react-hot-loader/patch',
            // 'webpack-dev-server/client?http://localhost:3001',
            // 'webpack/hot/only-dev-server',
            './Admin/Index'
        ],
        vendor: VENOR
  } ,
  output: {
    path: path.join(__dirname, 'dist'),
    filename: './[name].bundle.js',
    publicPath: '/static/',
    //加这个！
    // chunkFilename: '[name].[chunkhash:5].chunk.js',
    chunkFilename: '[name].js'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      // vendor 的意义和之前相同
      // manifest文件是将每次打包都会更改的东西单独提取出来，保证没有更改的代码无需重新打包，这样可以加快打包速度
        names: ['vendor', 'manifest','admin'],
        // 配合 manifest 文件使用
        minChunks: Infinity
    }),
    // 只删除 dist 文件夹下的 bundle 和 manifest 文件
    new CleanWebpackPlugin(['dist/*.bundle.js','dist/manifest.*.js'], {
      // 打印 log
        verbose: true,
        // 删除文件
        dry: false
      }),
      //压缩
    new webpack.optimize.UglifyJsPlugin({
        output: {
          comments: false,//去掉注释
        },
        compress: {
          warnings: false,//去掉警告
        }
      }),
      //压缩
      // new CompressionPlugin({
      //   asset: "[path].gz[query]",
      //   algorithm: "gzip",
      //   test: /\.js$|\.css$|\.html$/,
      //   threshold: 10240,
      //   minRatio: 0.8
      // }),
  ],
  resolve: {
    extensions: ['.js', '.jsx', '.less', '.scss', '.css'],
    modules: [
      path.resolve(__dirname, 'node_modules'),
      path.join(__dirname, './App'),
      path.join(__dirname, './Admin'),
      path.join(__dirname, './static')
    ]
  },
  module: {
    rules: [{
          test: /\.(js|jsx)$/,
          use: ['babel-loader'],
          exclude: /node_modules/,
          // include: path.join(__dirname, 'App')
      }, {
          test: /\.(less|css|scss)$/,
          use: ["style-loader", "css-loader", "sass-loader"]
      }, {
          test: /\.(png|jpg|gif|md)$/,
          use: ['file-loader?limit=10000&name=[md5:hash:base64:10].[ext]']
      }, {
          test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
          use: ['url-loader?limit=10000&mimetype=image/svg+xml']
      }, {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "url-loader?limit=10000&mimetype=application/font-woff"
      }, {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "file-loader"
      }
      // ,
      // { test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/,
      //   loader: 'url-loader?limit=50000&name=[path][name].[ext]'
      // }
    ],
  }
};
<commit_msg>commit<commit_after>var path = require('path');
var webpack = require('webpack');
var CleanWebpackPlugin = require('clean-webpack-plugin');
let CompressionPlugin = require("compression-webpack-plugin");//引入

const VENOR = [
"react",
"react-dom",
"react-lz-editor",
"mobx",
"mobx-react",
"react-router",
"react-router-dom",
"axios",
"bulma"
]

module.exports = {
  devtool: 'eval',
  entry: {
      // 'app':[
      //       'react-hot-loader/patch',
      //       'webpack-dev-server/client?http://localhost:3001',
      //       'webpack/hot/only-dev-server',
      //       './App/index',
      //   ],
        'admin':[
            'react-hot-loader/patch',
            // 'webpack-dev-server/client?http://localhost:3001',
            // 'webpack/hot/only-dev-server',
            './Admin/Index'
        ],
        vendor: VENOR
  } ,
  output: {
    path: path.join(__dirname, 'dist'),
    filename: './[name].bundle.js',
    publicPath: '/static/',
    //加这个！
    // chunkFilename: '[name].[chunkhash:5].chunk.js',
    chunkFilename: '[name].js'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      // vendor 的意义和之前相同
      // manifest文件是将每次打包都会更改的东西单独提取出来，保证没有更改的代码无需重新打包，这样可以加快打包速度
        names: ['vendor', 'manifest','admin'],
        // 配合 manifest 文件使用
        minChunks: Infinity
    }),
    // 只删除 dist 文件夹下的 bundle 和 manifest 文件
    // new CleanWebpackPlugin(['dist/*.bundle.js','dist/manifest.*.js'], {
    //   // 打印 log
    //     verbose: true,
    //     // 删除文件
    //     dry: false
    //   }),
      //压缩
    new webpack.optimize.UglifyJsPlugin({
        output: {
          comments: false,//去掉注释
        },
        compress: {
          warnings: false,//去掉警告
        }
      }),
      //压缩
      // new CompressionPlugin({
      //   asset: "[path].gz[query]",
      //   algorithm: "gzip",
      //   test: /\.js$|\.css$|\.html$/,
      //   threshold: 10240,
      //   minRatio: 0.8
      // }),
  ],
  resolve: {
    extensions: ['.js', '.jsx', '.less', '.scss', '.css'],
    modules: [
      path.resolve(__dirname, 'node_modules'),
      path.join(__dirname, './App'),
      path.join(__dirname, './Admin'),
      path.join(__dirname, './static')
    ]
  },
  module: {
    rules: [{
          test: /\.(js|jsx)$/,
          use: ['babel-loader'],
          exclude: /node_modules/,
          // include: path.join(__dirname, 'App')
      }, {
          test: /\.(less|css|scss)$/,
          use: ["style-loader", "css-loader", "sass-loader"]
      }, {
          test: /\.(png|jpg|gif|md)$/,
          use: ['file-loader?limit=10000&name=[md5:hash:base64:10].[ext]']
      }, {
          test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
          use: ['url-loader?limit=10000&mimetype=image/svg+xml']
      }, {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "url-loader?limit=10000&mimetype=application/font-woff"
      }, {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "file-loader"
      }
      // ,
      // { test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/,
      //   loader: 'url-loader?limit=50000&name=[path][name].[ext]'
      // }
    ],
  }
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path')
  , webpack = require('webpack');

const SRC_PATH = path.join(__dirname, 'src')
    , BUILD_PATH = path.join(__dirname, 'static')
    , VENDORS = ['node_modules', 'bower_components'];

const VENDOR_RE = new RegExp(VENDORS.join('|'));

// Check if module is vendor, for chunking
const isVendor = (module) => {
  var r = module.userRequest;
  return typeof r === 'string' && r.match(VENDOR_RE);
}

var config = {
  // What file to start at
  entry: [path.join(SRC_PATH, 'main.coffee')],

  // Where to output
  output: {
    path: BUILD_PATH,
    publicPath: '/static/',
    filename: '[name].js',
  },

  // Where to load modules and loaders from
  resolve: {
    modulesDirectories: VENDORS,
  },

  resolveLoader: {
    modulesDirectories: VENDORS,
  },

  // Coffeelint options
  coffeelint: {
    configFile: 'coffeelint.json',
  },

  // Stylus options
  stylus: {
    use: [require('nib')()],
    import: ['~nib/lib/nib/index.styl'],
    preferPathResolver: 'webpack',
  },

  // Stylint options
  stylint: {
    config: '.stylintrc',
  },

  module: {
    // Linters, etc
    preLoaders: [
      {
        test: /\.coffee$/,
        loader: 'coffee-lint',
        exclude: VENDOR_RE,
      },
      {
        test: /\.styl/,
        loader: 'stylint',
        exclude: VENDOR_RE,
      },
    ],

    // What to load
    loaders: [
      { // Coffeescript (DO NOT MOVE)
        test: /\.coffee$/,
        loaders: ['coffee'],
      },
      { // Stylus
        test: /\.styl$/,
        exclude: /\.u\.styl/,
        loaders: ['style', 'css', 'stylus'],
      },
      { // Reference-counted stylus
        test: /\.u\.styl/,
        loaders: ['style/useable', 'css', 'stylus'],
      },
      { // Plain CSS
        test: /\.css$/,
        loaders: ['style', 'css'],
      },
      { // Media
        test: /\.(png|jpe?g|gif|svg|woff|woff2|eot|ttf)$/,
        loaders: ['url'],
      },
    ],
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: isVendor,
    }),
  ],
};

// Production
if (process.env.NODE_ENV === 'production') {
  config.plugins.unshift(
    // Production environment variable
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production'),
      },
    }),

    // Deduplicate
    new webpack.optimize.DedupePlugin()
  );
  config.plugins.push(
    // Minify
    new webpack.optimize.UglifyJsPlugin({
      compress: {warnings: false},
    })
  );

// Development
} else {
  // Source maps
  config.devtool = 'eval';

  // -- Hot loading --

  config.entry.unshift('webpack/hot/only-dev-server');

  // loaders[0] is coffee
  config.module.loaders[0].loaders.unshift('react-hot-loader/webpack');
  config.plugins.unshift(new webpack.HotModuleReplacementPlugin());

  config.devServer = {
    // Adjust entry point
    inline: true,

    // Hot reloading
    hot: true,

    // Allow routing
    historyApiFallback: true,

    stats: {
      // Do not show list of hundreds of files included in a bundle
      chunkModules: false,
      colors: true,
    },
  };
}

module.exports = config;
<commit_msg>comments<commit_after>'use strict';

var path = require('path')
  , webpack = require('webpack');

const SRC_PATH = path.join(__dirname, 'src')
    , BUILD_PATH = path.join(__dirname, 'static')
    , VENDORS = ['node_modules', 'bower_components'];

const VENDOR_RE = new RegExp(VENDORS.join('|'));

// Check if module is vendor, for chunking
const isVendor = (module) => {
  var r = module.userRequest;
  return typeof r === 'string' && r.match(VENDOR_RE);
}

var config = {
  // What file to start at
  entry: [path.join(SRC_PATH, 'main.coffee')],

  // Where to output
  output: {
    path: BUILD_PATH,
    publicPath: '/static/',
    filename: '[name].js',
  },

  // Where to load modules from
  resolve: {
    modulesDirectories: VENDORS,
  },

  // Where to load loaders from
  resolveLoader: {
    modulesDirectories: VENDORS,
  },

  // Coffeelint options
  coffeelint: {
    configFile: 'coffeelint.json',
  },

  // Stylus options
  stylus: {
    use: [require('nib')()],
    import: ['~nib/lib/nib/index.styl'],
    preferPathResolver: 'webpack',
  },

  // Stylint options
  stylint: {
    config: '.stylintrc',
  },

  module: {
    // Linters, etc
    preLoaders: [
      { // Coffeelint
        test: /\.coffee$/,
        loader: 'coffee-lint',
        exclude: VENDOR_RE,
      },
      { // Stylint
        test: /\.styl/,
        loader: 'stylint',
        exclude: VENDOR_RE,
      },
    ],

    // What to load
    loaders: [
      { // Coffeescript (DO NOT MOVE)
        test: /\.coffee$/,
        loaders: ['coffee'],
      },
      { // Stylus
        test: /\.styl$/,
        exclude: /\.u\.styl/,
        loaders: ['style', 'css', 'stylus'],
      },
      { // Reference-counted stylus
        test: /\.u\.styl/,
        loaders: ['style/useable', 'css', 'stylus'],
      },
      { // Plain CSS
        test: /\.css$/,
        loaders: ['style', 'css'],
      },
      { // Media
        test: /\.(png|jpe?g|gif|svg|woff|woff2|eot|ttf)$/,
        loaders: ['url'],
      },
    ],
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: isVendor,
    }),
  ],
};

// Production
if (process.env.NODE_ENV === 'production') {
  config.plugins.unshift(
    // Production environment variable
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production'),
      },
    }),

    // Deduplicate
    new webpack.optimize.DedupePlugin()
  );
  config.plugins.push(
    // Minify
    new webpack.optimize.UglifyJsPlugin({
      compress: {warnings: false},
    })
  );

// Development
} else {
  // Source maps
  config.devtool = 'eval';

  // -- Hot loading --

  config.entry.unshift('webpack/hot/only-dev-server');

  // loaders[0] is coffee
  config.module.loaders[0].loaders.unshift('react-hot-loader/webpack');
  config.plugins.unshift(new webpack.HotModuleReplacementPlugin());

  config.devServer = {
    // Adjust entry point
    inline: true,

    // Hot reloading
    hot: true,

    // Allow routing
    historyApiFallback: true,

    stats: {
      // Do not show list of hundreds of files included in a bundle
      chunkModules: false,
      colors: true,
    },
  };
}

module.exports = config;
<|endoftext|>


<commit_before>/* eslint-env node */
const path = require("path");
const generateWebpackConfiguration = require("./scripts/generate_webpack_configuration.js");

const shouldMinify = !!process.env.RXP_MINIFY;
const isBarebone = process.env.RXP_BAREBONE === "true";

module.exports = generateWebpackConfiguration(
  "./src/exports.ts",
  {
    library: "RxPlayer",
    libraryTarget: "umd",
    path: path.join(__dirname, "dist"),
    filename: shouldMinify ? "rx-player.min.js" : "rx-player.js",
  },
  {
    maxEntrypointSize: shouldMinify ? 400000 : 1500000,
    maxAssetSize: shouldMinify ? 400000 : 1500000,
    minify: shouldMinify,
    features: {
      SMOOTH: isBarebone ?
        process.env.RXP_SMOOTH === "true" :
        process.env.RXP_SMOOTH !== "false",

      DASH: isBarebone ?
        process.env.RXP_DASH === "true" :
        process.env.RXP_DASH !== "false",

      DIRECTFILE: isBarebone ?
        process.env.RXP_DIRECTFILE === "true" :
        process.env.RXP_DIRECTFILE !== "false",

      NATIVE_TTML: isBarebone ?
        process.env.RXP_NATIVE_TTML === "true" :
        process.env.RXP_NATIVE_TTML !== "false",

      NATIVE_SAMI: isBarebone ?
        process.env.RXP_NATIVE_SAMI === "true" :
        process.env.RXP_NATIVE_SAMI !== "false",

      NATIVE_VTT: isBarebone ?
        process.env.RXP_NATIVE_VTT === "true" :
        process.env.RXP_NATIVE_VTT !== "false",

      NATIVE_SRT: isBarebone ?
        process.env.RXP_NATIVE_SRT === "true" :
        process.env.RXP_NATIVE_SRT !== "false",

      HTML_TTML: isBarebone ?
        process.env.RXP_HTML_TTML === "true" :
        process.env.RXP_HTML_TTML !== "false",

      HTML_SAMI: isBarebone ?
        process.env.RXP_HTML_SAMI === "true" :
        process.env.RXP_HTML_SAMI !== "false",

      HTML_VTT: isBarebone ?
        process.env.RXP_HTML_VTT === "true" :
        process.env.RXP_HTML_VTT !== "false",

      HTML_SRT: isBarebone ?
        process.env.RXP_HTML_SRT === "true" :
        process.env.RXP_HTML_SRT !== "false",

      EME: isBarebone ?
        process.env.RXP_EME === "true" :
        process.env.RXP_EME !== "false",

      BIF_IMAGES: isBarebone ?
        process.env.RXP_BIF_IMAGES === "true" :
        process.env.RXP_BIF_IMAGES !== "false",
    },
  }
);
<commit_msg>webpack: restore previous webpack configuration<commit_after>/* eslint-env node */

const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const webpack = require("webpack");

const RXP_ENV = process.env.RXP_ENV || "production";
const shouldMinify = !!process.env.RXP_MINIFY;
const isBarebone = process.env.RXP_BAREBONE === "true";

if (["development", "production"].indexOf(RXP_ENV) < 0) {
  throw new Error("unknown RXP_ENV " + RXP_ENV);
}

const isDevMode = RXP_ENV === "development";

const plugins = [
  new webpack.DefinePlugin({
    "__FEATURES__": {
      SMOOTH: isBarebone ?
        process.env.RXP_SMOOTH === "true" :
        process.env.RXP_SMOOTH !== "false",

      DASH: isBarebone ?
        process.env.RXP_DASH === "true" :
        process.env.RXP_DASH !== "false",

      DIRECTFILE: isBarebone ?
        process.env.RXP_DIRECTFILE === "true" :
        process.env.RXP_DIRECTFILE !== "false",

      NATIVE_TTML: isBarebone ?
        process.env.RXP_NATIVE_TTML === "true" :
        process.env.RXP_NATIVE_TTML !== "false",

      NATIVE_SAMI: isBarebone ?
        process.env.RXP_NATIVE_SAMI === "true" :
        process.env.RXP_NATIVE_SAMI !== "false",

      NATIVE_VTT: isBarebone ?
        process.env.RXP_NATIVE_VTT === "true" :
        process.env.RXP_NATIVE_VTT !== "false",

      NATIVE_SRT: isBarebone ?
        process.env.RXP_NATIVE_SRT === "true" :
        process.env.RXP_NATIVE_SRT !== "false",

      HTML_TTML: isBarebone ?
        process.env.RXP_HTML_TTML === "true" :
        process.env.RXP_HTML_TTML !== "false",

      HTML_SAMI: isBarebone ?
        process.env.RXP_HTML_SAMI === "true" :
        process.env.RXP_HTML_SAMI !== "false",

      HTML_VTT: isBarebone ?
        process.env.RXP_HTML_VTT === "true" :
        process.env.RXP_HTML_VTT !== "false",

      HTML_SRT: isBarebone ?
        process.env.RXP_HTML_SRT === "true" :
        process.env.RXP_HTML_SRT !== "false",

      // TODO
      // EME: isBarebone ?
      //   process.env.RXP_EME === "true" :
      //   process.env.RXP_EME !== "false",
      // BIF: isBarebone ?
      //   process.env.RXP_BIF === "true" :
      //   process.env.RXP_BIF !== "false",
    },
    __DEV__: isDevMode,
    __LOGGER_LEVEL__: isDevMode ? "\"INFO\"" : "\"DEBUG\"",
    "process.env": {
      NODE_ENV: JSON.stringify(isDevMode ? "development" : "production"),
    },
  }),
];

if (!isDevMode) {
  plugins.push(new BundleAnalyzerPlugin());
}

module.exports = {
  mode: isDevMode ? "development" : "production",
  entry: "./src/exports.ts",
  output: {
    library: "RxPlayer",
    libraryTarget: "umd",
    filename: shouldMinify ? "rx-player.min.js" : "rx-player.js",
  },
  optimization: {
    minimizer: shouldMinify ? [new UglifyJsPlugin()] : [
      new UglifyJsPlugin({
        uglifyOptions: {
          compress: { keep_infinity: true },
          keep_fnames: true,
          keep_classnames: true,
          keep_fargs: true,
          mangle: false,
          output: {
            beautify: true,
            comments: true,
          },
        },
      }),
    ],
  },
  performance: {
    maxEntrypointSize: shouldMinify ? 400000 : 1500000,
    maxAssetSize: shouldMinify ? 400000 : 1500000,
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx", ".json"],
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: "babel-loader",
            options: {
              cacheDirectory: true,
              presets: [
                [ "es2015", { loose: true, modules: false } ],
                "es2016",
                "es2017",
              ],
            },
          },
          { loader: "ts-loader" },
        ],
      },
    ],
  },
  plugins,
  node: {
    console: false,
    global: true,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
    setImmediate: false,
  },
};
<|endoftext|>


<commit_before>var SchemaPlugin = require('./schemaPlugin')
var webpack = require('webpack')

var plugins = [
  new SchemaPlugin(),
]

if (process.env.NODE_ENV === 'production')
  plugins.push(new webpack.optimize.UglifyJsPlugin({minimize: true}))

var config = {
  entry: './src/frontend/app.js',
  module: {
    noParse: /node_modules\/quill\/dist\/quill\.js/,
    loaders: [
      { test: /\.json$/, loader: 'json'},
      { test: /\.css$/, loader: "style!css" },
      {
        exclude: /node_modules/,
        loader: 'babel',
        query: {stage: 0, plugins: ['./webpack/babelRelayPlugin']},
        test: /\.js$/,
      }
    ]
  },
  plugins: plugins,
  output: {
    filename: 'app.js',
    path: './src/frontend/public/assets/js/'
  }
}

if (process.env.NODE_ENV === 'development') {
  config['devtool'] = "#inline-source-map";
} else if (process.env.NODE_ENV === 'production') {
  config['devtool'] = 'source-map';
}

module.exports = config
<commit_msg> specify newrelic as an external in WebPack as per https://discuss.newrelic.com/t/node-agent-fails-with-webpack/24874/2<commit_after>var SchemaPlugin = require('./schemaPlugin')
var webpack = require('webpack')

var plugins = [
  new SchemaPlugin(),
]

if (process.env.NODE_ENV === 'production')
  plugins.push(new webpack.optimize.UglifyJsPlugin({minimize: true}))

var config = {
  entry: './src/frontend/app.js',
  module: {
    noParse: /node_modules\/quill\/dist\/quill\.js/,
    loaders: [
      { test: /\.json$/, loader: 'json'},
      { test: /\.css$/, loader: "style!css" },
      {
        exclude: /node_modules/,
        loader: 'babel',
        query: {stage: 0, plugins: ['./webpack/babelRelayPlugin']},
        test: /\.js$/,
      }
    ]
  },
  plugins: plugins,
  output: {
    filename: 'app.js',
    path: './src/frontend/public/assets/js/'
  },
  externals: {
    // define newrelic as an external library
    // http://webpack.github.io/docs/configuration.html#externals
    newrelic: true
  }
}

if (process.env.NODE_ENV === 'development') {
  config['devtool'] = "#inline-source-map";
} else if (process.env.NODE_ENV === 'production') {
  config['devtool'] = 'source-map';
}

module.exports = config
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const { spawn } = require('child_process')
const readline = require('readline')
const YAML = require('js-yaml')
const gzipSize = require('gzip-size')
const prettierBytes = require('@transloadit/prettier-bytes')
const esbuild = require('esbuild')
const touch = require('touch')
const glob = require('glob')

const webRoot = __dirname
const uppyRoot = path.join(__dirname, '../packages/uppy')
const robodogRoot = path.join(__dirname, '../packages/@uppy/robodog')
const localesRoot = path.join(__dirname, '../packages/@uppy/locales')

const configPath = path.join(webRoot, '/themes/uppy/_config.yml')
// eslint-disable-next-line import/no-dynamic-require
const { version } = require(path.join(uppyRoot, '/package.json'))

const regionalDisplayNames = new Intl.DisplayNames('en-US', { type: 'region' })
const languageDisplayNames = new Intl.DisplayNames('en-US', { type: 'language' })

const defaultConfig = {
  comment: 'Auto updated by inject.js',
  uppy_version_anchor: '001',
  uppy_version: '0.0.1',
  uppy_bundle_kb_sizes: {},
  config: {},
}

// Keeping a whitelist so utils etc are excluded
// It may be easier to maintain a blacklist instead
const packages = [
  // Bundles
  'uppy',
  '@uppy/robodog',
  // Integrations
  '@uppy/react',
  // Core
  '@uppy/core',
  // Plugins -- please keep these sorted alphabetically
  '@uppy/aws-s3',
  '@uppy/aws-s3-multipart',
  '@uppy/dashboard',
  '@uppy/drag-drop',
  '@uppy/dropbox',
  '@uppy/file-input',
  '@uppy/form',
  '@uppy/golden-retriever',
  '@uppy/google-drive',
  '@uppy/informer',
  '@uppy/instagram',
  '@uppy/image-editor',
  '@uppy/progress-bar',
  '@uppy/screen-capture',
  '@uppy/status-bar',
  '@uppy/thumbnail-generator',
  '@uppy/transloadit',
  '@uppy/tus',
  '@uppy/url',
  '@uppy/webcam',
  '@uppy/xhr-upload',
  '@uppy/drop-target',
  // Stores
  '@uppy/store-default',
  '@uppy/store-redux',
]

const excludes = {
  '@uppy/react': ['react'],
}

// eslint-disable-next-line no-use-before-define
inject().catch((err) => {
  console.error(err)
  process.exit(1)
})

async function getMinifiedSize (pkg, name) {
  const packageJSON = fs.readFileSync(path.join(pkg, 'package.json'))
  // eslint-disable-next-line no-shadow
  const { main, version } = JSON.parse(packageJSON)

  const external = excludes[name] ?? []
  if (name !== '@uppy/core' && name !== 'uppy') {
    // Preact is already unconditionally included through @uppy/core
    external.unshift('@uppy/core', 'preact')
  }

  const { outputFiles:[{ contents: bundle }] } = await esbuild.build({
    write: false,
    bundle: true,
    entryPoints: [path.resolve(pkg, main)],
    minify: true,
    external,
  })
  const gzipped = await gzipSize(bundle)

  return {
    minified: bundle.length,
    gzipped,
    version,
  }
}

async function injectSizes (config) {
  console.info(chalk.grey('Generating bundle sizes…'))
  const padTarget = Math.max(...packages.map((cur) => cur.length)) + 2

  const sizesPromise = Promise.all(
    packages.map(async (pkg) => {
      const result = await getMinifiedSize(path.join(__dirname, '../packages', pkg), pkg)
      console.info(chalk.green(
        // ✓ @uppy/pkgname:     10.0 kB min  / 2.0 kB gz
        `  ✓ ${pkg}: ${' '.repeat(padTarget - pkg.length)}${
          `${prettierBytes(result.minified)} min`.padEnd(10)
        } / ${prettierBytes(result.gzipped)} gz`,
      ))
      return [pkg, {
        ...result,
        prettyMinified: prettierBytes(result.minified),
        prettyGzipped: prettierBytes(result.gzipped),
      }]
    }),
  ).then(Object.fromEntries)

  // eslint-disable-next-line no-param-reassign
  config.uppy_bundle_kb_sizes = await sizesPromise
}

const sourceUppy = path.join(webRoot, '/themes/uppy/source/uppy/')
const sourceUppyLocales = path.join(sourceUppy, 'locales')
async function injectBundles () {
  await Promise.all([
    fs.promises.mkdir(sourceUppy, { recursive:true }),
    fs.promises.mkdir(sourceUppyLocales, { recursive:true }),
  ])
  const cmds = [
    `cp -vfR ${path.join(uppyRoot, '/dist/*')} ${sourceUppy}`,
    `cp -vfR ${path.join(robodogRoot, '/dist/*')} ${sourceUppy}`,
    `cp -vfR ${path.join(localesRoot, '/dist/*')} ${sourceUppyLocales}`,
  ].join(' && ')

  const cp = spawn(cmds, { stdio:['ignore', 'pipe', 'inherit'], shell: true })
  await Promise.race([
    new Promise((resolve, reject) => cp.on('error', reject)),
    (async () => {
      const stdout = readline.createInterface({
        input: cp.stdout,
      })

      for await (const line of stdout) {
        console.info(chalk.green('✓ injected: '), chalk.grey(line))
      }
    })(),
  ])
}

// re-enable after rate limiter issue is fixed
//
async function injectGhStars () {
  const opts = {}
  if ('GITHUB_TOKEN' in process.env) {
    opts.auth = process.env.GITHUB_TOKEN
  }

  // eslint-disable-next-line global-require
  const { Octokit } = require('@octokit/rest')
  const octokit = new Octokit(opts)

  const { headers, data } = await octokit.repos.get({
    owner: 'transloadit',
    repo: 'uppy',
  })

  console.log(`${headers['x-ratelimit-remaining']} requests remaining until we hit GitHub ratelimiter`)

  const dstpath = path.join(webRoot, 'themes', 'uppy', 'layout', 'partials', 'generated_stargazers.ejs')
  fs.writeFileSync(dstpath, String(data.stargazers_count), 'utf-8')

  console.log(`${data.stargazers_count} stargazers written to '${dstpath}'`)
}

async function injectMarkdown () {
  const sources = {
    '.github/ISSUE_TEMPLATE/integration_help.md': 'src/_template/integration_help.md',
    '.github/CONTRIBUTING.md': 'src/_template/contributing.md',
  }

  for (const src of Object.keys(sources)) {
    const dst = sources[src]
    // strip yaml frontmatter:
    const srcpath = path.join(uppyRoot, `/../../${src}`)
    const dstpath = path.join(webRoot, dst)
    const parts = fs.readFileSync(srcpath, 'utf-8').split(/---\s*\n/)
    if (parts.length >= 3) {
      parts.shift()
      parts.shift()
    }
    let content = `<!-- WARNING! This file was injected. Please edit in "${src}" instead and run "${path.basename(__filename)}" -->\n\n`
    content += parts.join('---\n')
    fs.writeFileSync(dstpath, content, 'utf-8')
    console.info(chalk.green('✓ injected: '), chalk.grey(srcpath))
  }
  touch(path.join(webRoot, '/src/support.md'))
}

function injectLocaleList () {
  const mdTable = [
    `<!-- WARNING! This file was automatically injected. Please run "${path.basename(__filename)}" to re-generate -->\n\n`,
    '| %count% Locales | NPM                | CDN                 | Source on GitHub |',
    '| --------------- | ------------------ | ------------------- | ---------------- |',
  ]
  const mdRows = []
  const localeList = {}

  const localePackagePath = path.join(localesRoot, 'src', '*.js')
  // eslint-disable-next-line import/no-dynamic-require, global-require
  const localePackageVersion = require(path.join(localesRoot, 'package.json')).version

  glob.sync(localePackagePath).forEach((localePath) => {
    const localeName = path.basename(localePath, '.js')
    const [languageCode, regionCode, variant] = localeName.split(/[-_]/)

    const languageName = languageDisplayNames.of(languageCode)
    const regionName = regionalDisplayNames.of(regionCode)
    const npmPath = `<code class="raw"><a href="https://www.npmjs.com/package/@uppy/locales">@uppy/locales</a>/lib/${localeName}</code>`
    const cdnPath = `[\`${localeName}.min.js\`](https://releases.transloadit.com/uppy/locales/v${localePackageVersion}/${localeName}.min.js)`
    const githubSource = `[\`${localeName}.js\`](https://github.com/transloadit/uppy/blob/main/packages/%40uppy/locales/src/${localeName}.js)`
    const mdTableRow = `| ${languageName}<br/> <small>${regionName}</small>${variant ? `
(${variant})` : ''} | ${npmPath} | ${cdnPath} | ✏ ${githubSource} |`
    mdRows.push(mdTableRow)

    localeList[localeName] = `${languageName} (${regionName}${variant ? `, ${variant}` : ''})`
  })

  const resultingMdTable = mdTable.concat(mdRows.sort()).join('\n').replace('%count%', mdRows.length)

  const dstpath = path.join(webRoot, 'src', '_template', 'list_of_locale_packs.md')
  const localeListDstPath = path.join(webRoot, 'src', 'examples', 'locale_list.json')
  fs.writeFileSync(dstpath, `${resultingMdTable}\n`, 'utf-8')
  console.info(chalk.green('✓ injected: '), chalk.grey(dstpath))
  fs.writeFileSync(localeListDstPath, JSON.stringify(localeList), 'utf-8')
  console.info(chalk.green('✓ injected: '), chalk.grey(localeListDstPath))
}

async function readConfig () {
  try {
    const buf = await fs.promises.readFile(configPath, 'utf8')
    return YAML.safeLoad(buf)
  } catch (err) {
    return {}
  }
}

async function inject () {
  const config = await readConfig()

  await injectGhStars()

  await injectMarkdown()

  injectLocaleList()

  config.uppy_version = version
  config.uppy_version_anchor = version.replace(/[^\d]+/g, '')
  await injectSizes(config)

  const saveConfig = { ...defaultConfig, ...config }
  await fs.promises.writeFile(configPath, YAML.safeDump(saveConfig), 'utf-8')
  console.info(chalk.green('✓ rewritten: '), chalk.grey(configPath))

  try {
    await injectBundles()
  } catch (error) {
    console.error(
      chalk.red('x failed to inject: '),
      chalk.grey(`uppy bundle into site, because: ${error}`),
    )
    process.exit(1)
  }
}
<commit_msg>Fix website build<commit_after>const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const { spawn } = require('child_process')
const readline = require('readline')
const YAML = require('js-yaml')
const gzipSize = require('gzip-size')
const prettierBytes = require('@transloadit/prettier-bytes')
const esbuild = require('esbuild')
const touch = require('touch')
const glob = require('glob')

const webRoot = __dirname
const uppyRoot = path.join(__dirname, '../packages/uppy')
const robodogRoot = path.join(__dirname, '../packages/@uppy/robodog')
const localesRoot = path.join(__dirname, '../packages/@uppy/locales')

const configPath = path.join(webRoot, '/themes/uppy/_config.yml')
// eslint-disable-next-line import/no-dynamic-require
const { version } = require(path.join(uppyRoot, '/package.json'))

const regionalDisplayNames = new Intl.DisplayNames('en-US', { type: 'region' })
const languageDisplayNames = new Intl.DisplayNames('en-US', { type: 'language' })

const defaultConfig = {
  comment: 'Auto updated by inject.js',
  uppy_version_anchor: '001',
  uppy_version: '0.0.1',
  uppy_bundle_kb_sizes: {},
  config: {},
}

// Keeping a whitelist so utils etc are excluded
// It may be easier to maintain a blacklist instead
const packages = [
  // Bundles
  'uppy',
  '@uppy/robodog',
  // Integrations
  '@uppy/react',
  // Core
  '@uppy/core',
  // Plugins -- please keep these sorted alphabetically
  '@uppy/aws-s3',
  '@uppy/aws-s3-multipart',
  '@uppy/dashboard',
  '@uppy/drag-drop',
  '@uppy/dropbox',
  '@uppy/file-input',
  '@uppy/form',
  '@uppy/golden-retriever',
  '@uppy/google-drive',
  '@uppy/informer',
  '@uppy/instagram',
  '@uppy/image-editor',
  '@uppy/progress-bar',
  '@uppy/screen-capture',
  '@uppy/status-bar',
  '@uppy/thumbnail-generator',
  '@uppy/transloadit',
  '@uppy/tus',
  '@uppy/url',
  '@uppy/webcam',
  '@uppy/xhr-upload',
  '@uppy/drop-target',
  // Stores
  '@uppy/store-default',
  '@uppy/store-redux',
]

const excludes = {
  '@uppy/react': ['react'],
}

// eslint-disable-next-line no-use-before-define
inject().catch((err) => {
  console.error(err)
  process.exit(1)
})

async function getMinifiedSize (pkg, name) {
  const packageJSON = fs.readFileSync(path.join(pkg, 'package.json'))
  // eslint-disable-next-line no-shadow
  const { main, version } = JSON.parse(packageJSON)

  const external = excludes[name] ?? []
  if (name !== '@uppy/core' && name !== 'uppy') {
    // Preact is already unconditionally included through @uppy/core
    external.unshift('@uppy/core', 'preact')
  }

  const { outputFiles:[{ contents: bundle }] } = await esbuild.build({
    write: false,
    bundle: true,
    entryPoints: [path.resolve(pkg, main)],
    minify: true,
    external,
  })
  const gzipped = await gzipSize(bundle)

  return {
    minified: bundle.length,
    gzipped,
    version,
  }
}

async function injectSizes (config) {
  console.info(chalk.grey('Generating bundle sizes…'))
  const padTarget = Math.max(...packages.map((cur) => cur.length)) + 2

  const sizesPromise = Promise.all(
    packages.map(async (pkg) => {
      const result = await getMinifiedSize(path.join(__dirname, '../packages', pkg), pkg)
      console.info(chalk.green(
        // ✓ @uppy/pkgname:     10.0 kB min  / 2.0 kB gz
        `  ✓ ${pkg}: ${' '.repeat(padTarget - pkg.length)}${
          `${prettierBytes(result.minified)} min`.padEnd(10)
        } / ${prettierBytes(result.gzipped)} gz`,
      ))
      return [pkg, {
        ...result,
        prettyMinified: prettierBytes(result.minified),
        prettyGzipped: prettierBytes(result.gzipped),
      }]
    }),
  ).then(Object.fromEntries)

  // eslint-disable-next-line no-param-reassign
  config.uppy_bundle_kb_sizes = await sizesPromise
}

const sourceUppy = path.join(webRoot, '/themes/uppy/source/uppy/')
const sourceUppyLocales = path.join(sourceUppy, 'locales')
async function injectBundles () {
  await Promise.all([
    fs.promises.mkdir(sourceUppy, { recursive:true }),
    fs.promises.mkdir(sourceUppyLocales, { recursive:true }),
  ])
  const cmds = [
    `cp -vfR ${path.join(uppyRoot, '/dist/*')} ${sourceUppy}`,
    `cp -vfR ${path.join(robodogRoot, '/dist/*')} ${sourceUppy}`,
    `cp -vfR ${path.join(localesRoot, '/dist/*')} ${sourceUppyLocales}`,
  ].join(' && ')

  const cp = spawn(cmds, { stdio:['ignore', 'pipe', 'inherit'], shell: true })
  await Promise.race([
    new Promise((resolve, reject) => cp.on('error', reject)),
    (async () => {
      const stdout = readline.createInterface({
        input: cp.stdout,
      })

      for await (const line of stdout) {
        console.info(chalk.green('✓ injected: '), chalk.grey(line))
      }
    })(),
  ])
}

// re-enable after rate limiter issue is fixed
//
async function injectGhStars () {
  const opts = {}
  if ('GITHUB_TOKEN' in process.env) {
    opts.auth = process.env.GITHUB_TOKEN
  }

  // eslint-disable-next-line global-require
  const { Octokit } = require('@octokit/rest')
  const octokit = new Octokit(opts)

  const { headers, data } = await octokit.repos.get({
    owner: 'transloadit',
    repo: 'uppy',
  })

  console.log(`${headers['x-ratelimit-remaining']} requests remaining until we hit GitHub ratelimiter`)

  const dstpath = path.join(webRoot, 'themes', 'uppy', 'layout', 'partials', 'generated_stargazers.ejs')
  fs.writeFileSync(dstpath, String(data.stargazers_count), 'utf-8')

  console.log(`${data.stargazers_count} stargazers written to '${dstpath}'`)
}

async function injectMarkdown () {
  const sources = {
    '.github/CONTRIBUTING.md': 'src/_template/contributing.md',
  }

  for (const src of Object.keys(sources)) {
    const dst = sources[src]
    // strip yaml frontmatter:
    const srcpath = path.join(uppyRoot, `/../../${src}`)
    const dstpath = path.join(webRoot, dst)
    const parts = fs.readFileSync(srcpath, 'utf-8').split(/---\s*\n/)
    if (parts.length >= 3) {
      parts.shift()
      parts.shift()
    }
    let content = `<!-- WARNING! This file was injected. Please edit in "${src}" instead and run "${path.basename(__filename)}" -->\n\n`
    content += parts.join('---\n')
    fs.writeFileSync(dstpath, content, 'utf-8')
    console.info(chalk.green('✓ injected: '), chalk.grey(srcpath))
  }
  touch(path.join(webRoot, '/src/support.md'))
}

function injectLocaleList () {
  const mdTable = [
    `<!-- WARNING! This file was automatically injected. Please run "${path.basename(__filename)}" to re-generate -->\n\n`,
    '| %count% Locales | NPM                | CDN                 | Source on GitHub |',
    '| --------------- | ------------------ | ------------------- | ---------------- |',
  ]
  const mdRows = []
  const localeList = {}

  const localePackagePath = path.join(localesRoot, 'src', '*.js')
  // eslint-disable-next-line import/no-dynamic-require, global-require
  const localePackageVersion = require(path.join(localesRoot, 'package.json')).version

  glob.sync(localePackagePath).forEach((localePath) => {
    const localeName = path.basename(localePath, '.js')
    const [languageCode, regionCode, variant] = localeName.split(/[-_]/)

    const languageName = languageDisplayNames.of(languageCode)
    const regionName = regionalDisplayNames.of(regionCode)
    const npmPath = `<code class="raw"><a href="https://www.npmjs.com/package/@uppy/locales">@uppy/locales</a>/lib/${localeName}</code>`
    const cdnPath = `[\`${localeName}.min.js\`](https://releases.transloadit.com/uppy/locales/v${localePackageVersion}/${localeName}.min.js)`
    const githubSource = `[\`${localeName}.js\`](https://github.com/transloadit/uppy/blob/main/packages/%40uppy/locales/src/${localeName}.js)`
    const mdTableRow = `| ${languageName}<br/> <small>${regionName}</small>${variant ? `
(${variant})` : ''} | ${npmPath} | ${cdnPath} | ✏ ${githubSource} |`
    mdRows.push(mdTableRow)

    localeList[localeName] = `${languageName} (${regionName}${variant ? `, ${variant}` : ''})`
  })

  const resultingMdTable = mdTable.concat(mdRows.sort()).join('\n').replace('%count%', mdRows.length)

  const dstpath = path.join(webRoot, 'src', '_template', 'list_of_locale_packs.md')
  const localeListDstPath = path.join(webRoot, 'src', 'examples', 'locale_list.json')
  fs.writeFileSync(dstpath, `${resultingMdTable}\n`, 'utf-8')
  console.info(chalk.green('✓ injected: '), chalk.grey(dstpath))
  fs.writeFileSync(localeListDstPath, JSON.stringify(localeList), 'utf-8')
  console.info(chalk.green('✓ injected: '), chalk.grey(localeListDstPath))
}

async function readConfig () {
  try {
    const buf = await fs.promises.readFile(configPath, 'utf8')
    return YAML.safeLoad(buf)
  } catch (err) {
    return {}
  }
}

async function inject () {
  const config = await readConfig()

  await injectGhStars()

  await injectMarkdown()

  injectLocaleList()

  config.uppy_version = version
  config.uppy_version_anchor = version.replace(/[^\d]+/g, '')
  await injectSizes(config)

  const saveConfig = { ...defaultConfig, ...config }
  await fs.promises.writeFile(configPath, YAML.safeDump(saveConfig), 'utf-8')
  console.info(chalk.green('✓ rewritten: '), chalk.grey(configPath))

  try {
    await injectBundles()
  } catch (error) {
    console.error(
      chalk.red('x failed to inject: '),
      chalk.grey(`uppy bundle into site, because: ${error}`),
    )
    process.exit(1)
  }
}
<|endoftext|>