MarcoCabazal
11/20/2016 - 12:21 AM

Webpack Config for Webpack-Rails + CDN for production (Webpack 1.x - some minor differences may be encountered for Webpack 2+)

Webpack Config for Webpack-Rails + CDN for production (Webpack 1.x - some minor differences may be encountered for Webpack 2+)

const CDN = process.env['CDN_HOST'] || '';

/**
 * Webpack configuration for integrating Webpack with Rails via the webpack-rails gem 
 * (https://github.com/mipearson/webpack-rails)
 * 
 * Cache-Busting Strategy:
 *   Development: Change query string of resource when content MD5 hash changes, 
 *                rewriting the asset in place but triggering rewrite of the manifest.
 *   Production:  Use MD5 hash of asset as filename, writing new assets and manifest 
 *                on each build. Files with unchanged content would be overwritten but cache 
 *                would stay valid. Only do this when old files can be cleaned out regularly, 
 *                ie, as part of Heroku deployment or AWS build pipeline.
 */

const config = {
    output: {
        path: production 
            ? path.resolve(appRoot, 'public', 'webpack') 
            : path.resolve(appRoot, 'public', 'webpack'),
        publicPath: production 
            ? CDN + '/webpack/' 
            : '/webpack/',
        filename: production 
            ? '[name]_application--[chunkhash].js' 
            : '[name]_application.js?[chunkhash]',
        devtoolModuleFilenameTemplate: '[resourcePath]',
        devtoolFallbackModuleFilenameTemplate: '[resourcePath]?[hash]',
    },
  
    module: {
        loaders: [
            {
                test: /.jsx$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    plugins: ['transform-es2015-modules-commonjs'],
                    presets: ['es2015', 'react'],
                },
            },
            {
                test: /\.(scss|sass)$/,
                loaders: [
                    'style',
                    'css?sourceMap&modules,localIdentName=' + 
                    (production 
                        ? '[hash:base64:8]' 
                        : '[local]--[hash:base64:8]'),
                    'sass?sourceMap',
                ],
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loader: production 
                    ? 'url?limit=1000&name=[hash].[ext]'
                    : 'url?limit=1000&name=[name].[ext]?[hash]',
            },
        ],
    },
  
    // Further configuration here ...
  
}