webpack-rails-0.9.11/0000755000004100000410000000000013213760162014357 5ustar www-datawww-datawebpack-rails-0.9.11/Rakefile0000644000004100000410000000104113213760162016020 0ustar www-datawww-databegin require 'bundler/setup' rescue LoadError puts 'You must `gem install bundler` and `bundle install` to run rake tasks' end require 'rdoc/task' require 'rspec/core/rake_task' require 'rubocop/rake_task' RuboCop::RakeTask.new RSpec::Core::RakeTask.new(:spec) RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'WebpackRails' rdoc.options << '--line-numbers' rdoc.rdoc_files.include('README.md') rdoc.rdoc_files.include('lib/**/*.rb') end Bundler::GemHelper.install_tasks task default: [:rubocop, :spec] webpack-rails-0.9.11/MIT-LICENSE0000644000004100000410000000203713213760162016015 0ustar www-datawww-dataCopyright 2015 Michael Pearson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. webpack-rails-0.9.11/webpack-rails.gemspec0000644000004100000410000000326113213760162020452 0ustar www-datawww-data######################################################### # This file has been automatically generated by gem2tgz # ######################################################### # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "webpack-rails" s.version = "0.9.11" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Michael Pearson"] s.date = "2017-08-17" s.description = "No longer maintained - use webpacker instead." s.email = ["mipearson@gmail.com"] s.files = ["MIT-LICENSE", "README.md", "Rakefile", "example/Procfile", "example/dot_gitignore", "example/package.json", "example/webpack.config.js", "lib/generators/webpack_rails/install_generator.rb", "lib/tasks/webpack.rake", "lib/webpack-rails.rb", "lib/webpack/rails.rb", "lib/webpack/rails/helper.rb", "lib/webpack/rails/manifest.rb", "lib/webpack/rails/version.rb", "lib/webpack/railtie.rb"] s.homepage = "http://github.com/mipearson/webpack-rails" s.licenses = ["MIT"] s.require_paths = ["lib"] s.required_ruby_version = Gem::Requirement.new(">= 2.0.0") s.rubygems_version = "1.8.23" s.summary = "No longer maintained - use webpacker instead." if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q, [">= 3.2.0"]) s.add_runtime_dependency(%q, [">= 3.2.0"]) else s.add_dependency(%q, [">= 3.2.0"]) s.add_dependency(%q, [">= 3.2.0"]) end else s.add_dependency(%q, [">= 3.2.0"]) s.add_dependency(%q, [">= 3.2.0"]) end end webpack-rails-0.9.11/lib/0000755000004100000410000000000013213760162015125 5ustar www-datawww-datawebpack-rails-0.9.11/lib/webpack/0000755000004100000410000000000013213760162016541 5ustar www-datawww-datawebpack-rails-0.9.11/lib/webpack/rails/0000755000004100000410000000000013213760162017653 5ustar www-datawww-datawebpack-rails-0.9.11/lib/webpack/rails/manifest.rb0000644000004100000410000000712113213760162022007 0ustar www-datawww-datarequire 'net/http' require 'uri' module Webpack module Rails # Webpack manifest loading, caching & entry point retrieval class Manifest # Raised if we can't read our webpack manifest for whatever reason class ManifestLoadError < StandardError def initialize(message, orig) super "#{message} (original error #{orig})" end end # Raised if webpack couldn't build one of your entry points class WebpackError < StandardError def initialize(errors) super "Error in webpack compile, details follow below:\n#{errors.join("\n\n")}" end end # Raised if a supplied entry point does not exist in the webpack manifest class EntryPointMissingError < StandardError end class << self # :nodoc: def asset_paths(source) raise WebpackError, manifest["errors"] unless manifest_bundled? paths = manifest["assetsByChunkName"][source] if paths # Can be either a string or an array of strings. # Do not include source maps as they are not javascript [paths].flatten.reject { |p| p =~ /.*\.map$/ }.map do |p| "/#{::Rails.configuration.webpack.public_path}/#{p}" end else raise EntryPointMissingError, "Can't find entry point '#{source}' in webpack manifest" end end private def manifest_bundled? !manifest["errors"].any? { |error| error.include? "Module build failed" } end def manifest if ::Rails.configuration.webpack.dev_server.enabled # Don't cache if we're in dev server mode, manifest may change ... load_manifest else # ... otherwise cache at class level, as JSON loading/parsing can be expensive @manifest ||= load_manifest end end def load_manifest data = if ::Rails.configuration.webpack.dev_server.enabled load_dev_server_manifest else load_static_manifest end JSON.parse(data) end def load_dev_server_manifest host = ::Rails.configuration.webpack.dev_server.manifest_host port = ::Rails.configuration.webpack.dev_server.manifest_port http = Net::HTTP.new(host, port) http.use_ssl = ::Rails.configuration.webpack.dev_server.https http.verify_mode = ::Rails.configuration.webpack.dev_server.https_verify_peer ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE http.get(dev_server_path).body rescue => e raise ManifestLoadError.new("Could not load manifest from webpack-dev-server at http://#{host}:#{port}#{dev_server_path} - is it running, and is stats-webpack-plugin loaded?", e) end def load_static_manifest File.read(static_manifest_path) rescue => e raise ManifestLoadError.new("Could not load compiled manifest from #{static_manifest_path} - have you run `rake webpack:compile`?", e) end def static_manifest_path ::Rails.root.join( ::Rails.configuration.webpack.output_dir, ::Rails.configuration.webpack.manifest_filename ) end def dev_server_path "/#{::Rails.configuration.webpack.public_path}/#{::Rails.configuration.webpack.manifest_filename}" end def dev_server_url "http://#{::Rails.configuration.webpack.dev_server.host}:#{::Rails.configuration.webpack.dev_server.port}#{dev_server_path}" end end end end end webpack-rails-0.9.11/lib/webpack/rails/helper.rb0000644000004100000410000000230213213760162021454 0ustar www-datawww-datarequire 'action_view' require 'webpack/rails/manifest' module Webpack module Rails # Asset path helpers for use with webpack module Helper # Return asset paths for a particular webpack entry point. # # Response may either be full URLs (eg http://localhost/...) if the dev server # is in use or a host-relative URl (eg /webpack/...) if assets are precompiled. # # Will raise an error if our manifest can't be found or the entry point does # not exist. def webpack_asset_paths(source, extension: nil) return "" unless source.present? paths = Webpack::Rails::Manifest.asset_paths(source) paths = paths.select { |p| p.ends_with? ".#{extension}" } if extension port = ::Rails.configuration.webpack.dev_server.port protocol = ::Rails.configuration.webpack.dev_server.https ? 'https' : 'http' host = ::Rails.configuration.webpack.dev_server.host host = instance_eval(&host) if host.respond_to?(:call) if ::Rails.configuration.webpack.dev_server.enabled paths.map! do |p| "#{protocol}://#{host}:#{port}#{p}" end end paths end end end end webpack-rails-0.9.11/lib/webpack/rails/version.rb0000644000004100000410000000011313213760162021660 0ustar www-datawww-datamodule Webpack # :nodoc: module Rails VERSION = "0.9.11" end end webpack-rails-0.9.11/lib/webpack/rails.rb0000644000004100000410000000012713213760162020200 0ustar www-datawww-datarequire 'webpack/rails/version' require 'webpack/railtie' if defined? ::Rails::Railtie webpack-rails-0.9.11/lib/webpack/railtie.rb0000644000004100000410000000332013213760162020515 0ustar www-datawww-datarequire 'rails' require 'rails/railtie' require 'webpack/rails/helper' module Webpack # :nodoc: class Railtie < ::Rails::Railtie config.after_initialize do ActiveSupport.on_load(:action_view) do include Webpack::Rails::Helper end end config.webpack = ActiveSupport::OrderedOptions.new config.webpack.dev_server = ActiveSupport::OrderedOptions.new config.webpack.config_file = 'config/webpack.config.js' config.webpack.binary = 'node_modules/.bin/webpack' # Host & port to use when generating asset URLS in the manifest helpers in dev # server mode. Defaults to the requested host rather than localhost, so # that requests from remote hosts work. config.webpack.dev_server.host = proc { respond_to?(:request) ? request.host : 'localhost' } config.webpack.dev_server.port = 3808 # The host and port to use when fetching the manifest # This is helpful for e.g. docker containers, where the host and port you # use via the web browser is not the same as those that the containers use # to communicate among each other config.webpack.dev_server.manifest_host = 'localhost' config.webpack.dev_server.manifest_port = 3808 config.webpack.dev_server.https = false # Below will default to 'true' in 1.0 release config.webpack.dev_server.https_verify_peer = false config.webpack.dev_server.binary = 'node_modules/.bin/webpack-dev-server' config.webpack.dev_server.enabled = ::Rails.env.development? || ::Rails.env.test? config.webpack.output_dir = "public/webpack" config.webpack.public_path = "webpack" config.webpack.manifest_filename = "manifest.json" rake_tasks do load "tasks/webpack.rake" end end end webpack-rails-0.9.11/lib/webpack-rails.rb0000644000004100000410000000003013213760162020167 0ustar www-datawww-datarequire 'webpack/rails' webpack-rails-0.9.11/lib/generators/0000755000004100000410000000000013213760162017276 5ustar www-datawww-datawebpack-rails-0.9.11/lib/generators/webpack_rails/0000755000004100000410000000000013213760162022104 5ustar www-datawww-datawebpack-rails-0.9.11/lib/generators/webpack_rails/install_generator.rb0000644000004100000410000000324713213760162026153 0ustar www-datawww-datamodule WebpackRails # :nodoc: class InstallGenerator < ::Rails::Generators::Base source_root File.expand_path("../../../../example", __FILE__) desc "Install everything you need for a basic webpack-rails integration" def add_foreman_to_gemfile gem 'foreman' end def copy_procfile copy_file "Procfile", "Procfile" end def copy_package_json copy_file "package.json", "package.json" end def copy_webpack_conf copy_file "webpack.config.js", "config/webpack.config.js" end def create_webpack_application_js empty_directory "webpack" create_file "webpack/application.js" do <<-EOF.strip_heredoc console.log("Hello world!"); EOF end end def add_to_gitignore append_to_file ".gitignore" do <<-EOF.strip_heredoc # Added by webpack-rails /node_modules /public/webpack EOF end end def run_yarn_install run "yarn install" if yes?("Would you like us to run 'yarn install' for you?") end def run_bundle_install run "bundle install" if yes?("Would you like us to run 'bundle install' for you?") end def whats_next puts <<-EOF.strip_heredoc We've set up the basics of webpack-rails for you, but you'll still need to: 1. Add the 'application' entry point in to your layout, and 2. Run 'foreman start' to run the webpack-dev-server and rails server See the README.md for this gem at https://github.com/mipearson/webpack-rails/blob/master/README.md for more info. Thanks for using webpack-rails! EOF end end end webpack-rails-0.9.11/lib/tasks/0000755000004100000410000000000013213760162016252 5ustar www-datawww-datawebpack-rails-0.9.11/lib/tasks/webpack.rake0000644000004100000410000000123613213760162020534 0ustar www-datawww-datanamespace :webpack do desc "Compile webpack bundles" task compile: :environment do ENV["TARGET"] = 'production' # TODO: Deprecated, use NODE_ENV instead ENV["NODE_ENV"] ||= 'production' webpack_bin = ::Rails.root.join(::Rails.configuration.webpack.binary) config_file = ::Rails.root.join(::Rails.configuration.webpack.config_file) unless File.exist?(webpack_bin) raise "Can't find our webpack executable at #{webpack_bin} - have you run `npm install`?" end unless File.exist?(config_file) raise "Can't find our webpack config file at #{config_file}" end sh "#{webpack_bin} --config #{config_file} --bail" end end webpack-rails-0.9.11/example/0000755000004100000410000000000013213760162016012 5ustar www-datawww-datawebpack-rails-0.9.11/example/dot_gitignore0000644000004100000410000000030013213760162020563 0ustar www-datawww-data # Ignore bundler config. /.bundle # Ignore all logfiles and tempfiles. /log/* !/log/.keep /tmp # Don't commit node_modules (vendored npm bits) or built assets /node_modules /public/webpack webpack-rails-0.9.11/example/package.json0000644000004100000410000000031513213760162020277 0ustar www-datawww-data{ "name": "webpack-rails-example", "version": "0.0.1", "license": "MIT", "dependencies": { "stats-webpack-plugin": "^0.4.3", "webpack": "^1.14.0", "webpack-dev-server": "^1.16.2" } } webpack-rails-0.9.11/example/Procfile0000644000004100000410000000027313213760162017502 0ustar www-datawww-data# Run Rails & Webpack concurrently # Example file from webpack-rails gem rails: bundle exec rails server webpack: ./node_modules/.bin/webpack-dev-server --config config/webpack.config.js webpack-rails-0.9.11/example/webpack.config.js0000644000004100000410000000352713213760162021237 0ustar www-datawww-data// Example webpack configuration with asset fingerprinting in production. 'use strict'; var path = require('path'); var webpack = require('webpack'); var StatsPlugin = require('stats-webpack-plugin'); // must match config.webpack.dev_server.port var devServerPort = 3808; // set NODE_ENV=production on the environment to add asset fingerprints var production = process.env.NODE_ENV === 'production'; var config = { entry: { // Sources are expected to live in $app_root/webpack 'application': './webpack/application.js' }, output: { // Build assets directly in to public/webpack/, let webpack know // that all webpacked assets start with webpack/ // must match config.webpack.output_dir path: path.join(__dirname, '..', 'public', 'webpack'), publicPath: '/webpack/', filename: production ? '[name]-[chunkhash].js' : '[name].js' }, resolve: { root: path.join(__dirname, '..', 'webpack') }, plugins: [ // must match config.webpack.manifest_filename new StatsPlugin('manifest.json', { // We only need assetsByChunkName chunkModules: false, source: false, chunks: false, modules: false, assets: true })] }; if (production) { config.plugins.push( new webpack.NoErrorsPlugin(), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false }, sourceMap: false }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin() ); } else { config.devServer = { port: devServerPort, headers: { 'Access-Control-Allow-Origin': '*' } }; config.output.publicPath = '//localhost:' + devServerPort + '/webpack/'; // Source maps config.devtool = 'cheap-module-eval-source-map'; } module.exports = config; webpack-rails-0.9.11/README.md0000644000004100000410000001546213213760162015646 0ustar www-datawww-data# No Longer Maintained Hi! `webpack-rails` is no longer being maintained. Please see #90 for more info. [![Build Status](https://travis-ci.org/mipearson/webpack-rails.svg?branch=master)](https://travis-ci.org/mipearson/webpack-rails) [![Gem Version](https://badge.fury.io/rb/webpack-rails.svg)](http://badge.fury.io/rb/webpack-rails) # webpack-rails **webpack-rails** gives you tools to integrate Webpack in to an existing Ruby on Rails application. It will happily co-exist with sprockets but does not use it for production fingerprinting or asset serving. **webpack-rails** is designed with the assumption that if you're using Webpack you treat Javascript as a first-class citizen. This means that you control the webpack config, package.json, and use yarn to install Webpack & its plugins. In development mode [webpack-dev-server](http://webpack.github.io/docs/webpack-dev-server.html) is used to serve webpacked entry points and offer hot module reloading. In production entry points are built in to `public/webpack`. **webpack-rails** uses [stats-webpack-plugin](https://www.npmjs.com/package/stats-webpack-plugin) to translate entry points in to asset paths. It was designed for use at [Marketplacer](http://www.marketplacer.com) to assist us in migrating our Javascript (and possibly our SCSS) off of Sprockets. It first saw production use in June 2015. Our examples show **webpack-rails** co-existing with sprockets (as that's how environment works), but sprockets is not used or required for development or production use of this gem. This gem has been tested against Rails 4.2 and Ruby 2.2. Earlier versions of Rails (>= 3.2) and Ruby (>= 2.0) may work, but we haven't tested them. ## Using webpack-rails **We have a demo application: [webpack-rails-demo](https://github.com/mipearson/webpack-rails-demo)** ### Installation 1. Install [yarn](https://yarnpkg.com/en/docs/install) if you haven't already 1. Add `webpack-rails` to your gemfile 1. Run `bundle install` to install the gem 1. Run `bundle exec rails generate webpack_rails:install` to copy across example files 1. Run `foreman start` to start `webpack-dev-server` and `rails server` at the same time 1. Add the webpack entry point to your layout (see next section) 1. Edit `webpack/application.js` and write some code ### Adding the entry point to your Rails application To add your webpacked javascript in to your app, add the following to the `` section of your to your `layout.html.erb`: ```erb <%= javascript_include_tag *webpack_asset_paths("application") %> ``` Take note of the splat (`*`): `webpack_asset_paths` returns an array, as one entry point can map to multiple paths, especially if hot reloading is enabled in Webpack. If your webpack is configured to output both CSS and JS, you can use the `extension:` argument to filter which files are returned by the helper: ```erb <%= javascript_include_tag *webpack_asset_paths('application', extension: 'js') %> <%= stylesheet_link_tag *webpack_asset_paths('application', extension: 'css') %> ``` #### Use with webpack-dev-server live reload If you're using the webpack dev server's live reload feature (not the React hot reloader), you'll also need to include the following in your layout template: ``` html ``` ### How it works Have a look at the files in the `examples` directory. Of note: * We use [foreman](https://github.com/ddollar/foreman) and a `Procfile` to run our rails server & the webpack dev server in development at the same time * The webpack and gem configuration must be in sync - look at our railtie for configuration options * We require that **stats-webpack-plugin** is loaded to automatically generate a production manifest & resolve paths during development ### Configuration Defaults * Webpack configuration lives in `config/webpack.config.js` * Webpack & Webpack Dev Server binaries are in `node_modules/.bin/` * Webpack Dev Server will run on port 3808 on localhost via HTTP * Webpack Dev Server is enabled in development & test, but not in production * Webpacked assets will be compiled to `public/webpack` * The manifest file is named `manifest.json` #### Dynamic host To have the host evaluated at request-time, set `host` to a proc: ```ruby config.webpack.dev_server.host = proc { request.host } ``` This is useful when accessing your Rails app over the network (remember to bind both your Rails app and your WebPack server to `0.0.0.0`). #### Use with docker-compose If you're running `webpack-dev-server` as part of docker compose rather than `foreman`, you might find that the host and port that rails needs to use to retrieve the manifest isn't the same as the host and port that you'll be giving to the browser to retrieve the assets. If so, you can set the `manifest_host` and `manifest_port` away from their default of `localhost` and port 3808. ### Working with browser tests In development, we make sure that the `webpack-dev-server` is running when browser tests are running. #### Continuous Integration In CI, we manually run `webpack` to compile the assets to public and set `config.webpack.dev_server.enabled` to `false` in our `config/environments/test.rb`: ``` ruby config.webpack.dev_server.enabled = !ENV['CI'] ``` ### Production Deployment Add `rake webpack:compile` to your deployment. It serves a similar purpose as Sprockets' `assets:precompile` task. If you're using Webpack and Sprockets (as we are at Marketplacer) you'll need to run both tasks - but it doesn't matter which order they're run in. If you deploy to Heroku, you can add the special [webpack-rails-buildpack](https://github.com/febeling/webpack-rails-buildpack) in order to perform this rake task on each deployment. If you're using `[chunkhash]` in your build asset filenames (which you should be, if you want to cache them in production), you'll need to persist built assets between deployments. Consider in-flight requests at the time of deployment: they'll receive paths based on the old `manifest.json`, not the new one. ## TODO * Drive config via JSON, have webpack.config.js read same JSON? * Custom webpack-dev-server that exposes errors, stats, etc * [react-rails](https://github.com/reactjs/react-rails) fork for use with this workflow * Integration tests ## Contributing Pull requests & issues welcome. Advice & criticism regarding webpack config approach also welcome. Please ensure that pull requests pass both rubocop & rspec. New functionality should be discussed in an issue first. ## Acknowledgements * Len Garvey for his [webpack-rails](https://github.com/lengarvey/webpack-rails) gem which inspired this implementation * Sebastian Porto for [Rails with Webpack](https://reinteractive.net/posts/213-rails-with-webpack-why-and-how) * Clark Dave for [How to use Webpack with Rails](http://clarkdave.net/2015/01/how-to-use-webpack-with-rails/)