Skip to content

Instantly share code, notes, and snippets.

@Swizec
Last active October 3, 2015 16:15
Show Gist options
  • Save Swizec/fb0905ba078520117c17 to your computer and use it in GitHub Desktop.
Save Swizec/fb0905ba078520117c17 to your computer and use it in GitHub Desktop.
Webpack rails configs
# lib/tasks/assets.rake
# The webpack task must run before assets:environment task.
# Otherwise Sprockets cannot find the files that webpack produces.
Rake::Task["assets:precompile"]
.clear_prerequisites
.enhance(["assets:compile_environment"])
namespace :assets do
# In this task, set prerequisites for the assets:precompile task
task compile_environment: :webpack do
Rake::Task["assets:environment"].invoke
end
desc "Compile assets with webpack"
task :webpack do
sh "$(npm bin)/webpack --config webpack.rails.config.js"
path = "app/assets/javascripts/generated/"
FileUtils.copy_file(Pathname.glob(path+'0.*.rails-bundle.js').first,
File.join(path, 'rails-bundle.js'))
end
end
const path = require('path');
const webpack = require('webpack');
var config = module.exports = {
context: __dirname,
entry: [
'./app/assets/javascripts/MathCrunchApp'
]
};
config.resolve = {
extensions: ['', '.json', '.js']
};
config.loaders = [
{include: /\.json$/, loaders: ['json-loader']}
];
config.externals = {};
[['jquery', 'jQuery'],
['jquery', '$'],
['lodash', '_'],
['backbone', 'Backbone'],
['handlebars', 'Handlebars'],
['string', 'string']
].forEach(function (lib) {
if (!lib) return;
var name = lib[0],
variable = lib[1];
config.loaders.push(
{test: require.resolve(name), loader: 'expose?'+variable}
);
config.externals[name] = 'var '+variable;
});
const config = require('./webpack.common.config');
config.output = {
filename: in_dev()
? 'rails-bundle.js'
: '[id].[chunkhash].rails-bundle.js',
path: 'app/assets/javascripts/generated',
publicPath: getCDN()+'/assets/generated/'
};
config.loaders.push(
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
);
module.exports = config;
function getCDN() {
var CDNs = {
staging: '<staging-id>.cloudfront.net',
production: '<production-id>.cloudfront.net',
preproduction: '<preproduction-id>.cloudfront.net'
};
if (!in_dev()) {
return "//"+CDNs[process.env.RAILS_ENV.toLowerCase()];
}
return "";
};
function in_dev() {
return !process.env.RAILS_ENV || process.env.RAILS_ENV == 'development';
}
// Heroku specific
const devBuild = (typeof process.env.BUILDPACK_URL) === 'undefined';
if (devBuild) {
console.log('Webpack dev build for Rails'); // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map';
} else {
console.log('Webpack production build for Rails'); // eslint-disable-line no-console
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment