Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Justin808/webpacker integration #822

Merged
merged 24 commits into from
May 6, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ node_package/tests/node_modules
node_package/webpack.config.js
**/node_modules/**
**/assets/webpack/**
**/public/webpack/**
**/generated/**
**/app/assets/javascripts/application.js
**/coverage/**
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

/spec/examples.txt
/spec/dummy/client/node_modules
/spec/dummy/app/assets/webpack/
/spec/dummy/public/webpack/
/spec/dummy/coverage/
/spec/react_on_rails/dummy-for-generators/

Expand Down
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,25 @@ Contributors: please follow the recommendations outlined at [keepachangelog.com]
## [Unreleased]
*Please add entries here for your pull requests.*

## [8.0.0] - 2017-05-03

### Added
Support for WebpackerLite in the generators. [#822](https://github.com/shakacode/react_on_rails/pull/822) by [kaizencodes](https://github.com/kaizencodes) and [justin808](https://github.com/justin808).

1. You do not need to switch to WebpackerLite to use 8.0.0.
2. You can find an upgrade example in [react-webpack-rails-tutorial PR #387](https://github.com/shakacode/react-webpack-rails-tutorial/pull/387).

### Changed
Breaking change is that the default value of symlink_non_digested_assets_regex has changed from this
old value to nil. This is a breaking change if you didn't have this value set in your
config/initializers/react_on_rails.rb file and you need this because you're using webpack's CSS
features and you have not switched to webpacker lite.

```
symlink_non_digested_assets_regex: /\.(png|jpg|jpeg|gif|tiff|woff|ttf|eot|svg|map)/,
```


## [7.0.4] - 2017-04-27
- Return empty json when nil in json_safe_and_pretty [#824](https://github.com/shakacode/react_on_rails/pull/824) by [dzirtusss](https://github.com/dzirtusss)

Expand Down
14 changes: 9 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

**For a complete example of this gem, see our live demo at [www.reactrails.com](http://www.reactrails.com). ([Source Code](https://github.com/shakacode/react-webpack-rails-tutorial))**

**Speaking!**: Justin is speaking [GORUCO](http://goruco.com/#speakers) on Saturday, June 24, 2017 in NYC: "Front-End Sadness to Happiness: The React on Rails Story". [Email Justin](mailto:justin@shakacode.com) to give this talk at your local meetup or company. [Subscribe](https://app.mailerlite.com/webforms/landing/l1d9x5) to be notified of local and *online* presentations of this talk.
**Speaking!**: Justin is speaking [GORUCO](http://goruco.com/#speakers) on Saturday, June 24, 2017 in NYC: "Front-End Sadness to Happiness: The React on Rails Story". [Email Justin](mailto:justin@shakacode.com) to give this talk at your local meetup or company. [Subscribe](https://app.mailerlite.com/webforms/landing/l1d9x5) to be notified of local and *online* presentations of this talk.

**Aloha from Justin Gordon** ([bio](http://www.railsonmaui.com/about)) and the [ShakaCode](http://www.shakacode.com) Team! We're actively looking for new projects involving React, React-Native, and Rails, including conversion of AngularJs to React. Please [contact me](mailto:justin@shakacode.com) if we could potentially help you in any way. Besides consulting on bigger projects, [ShakaCode](http://www.shakacode.com) is doing ScreenHero plus Slack/Github based [coaching](http://www.shakacode.com/work/shakacode-coaching-plan.pdf) for React on Rails. See our blog post [Can ShakaCode Help You?](https://blog.shakacode.com/can-shakacode-help-you-4a5b1e5a8a63#.jex6tg9w9) for more information.

Expand Down Expand Up @@ -49,7 +49,7 @@ For more testimonials, see [Live Projects](PROJECTS.md) and [Kudos](./KUDOS.md).
* [284 Ruby Rogues: React on Rails with Justin Gordon and Rob Wise](https://devchat.tv/ruby-rogues/284-rr-react-on-rails-with-justin-gordon-and-rob-wise)

# NEWS
* 2017-04-25: 7.0.0 Shipped! Performance improvements! Please upgrade! Only "breaking" change is that you have to update both the node module and the Ruby gem.
* 2017-04-25: 7.0.0 Shipped! Performance improvements! Please upgrade! Only "breaking" change is that you have to update both the node module and the Ruby gem.
* 2017-04-09: 8.0.0 beta work to include webpacker_lite gem has begun. See [#786](https://github.com/shakacode/react_on_rails/issues/786).
* *See [NEWS.md](NEWS.md) for more notes over time.*

Expand Down Expand Up @@ -106,6 +106,10 @@ Universal React with Rails: Part I](https://medium.com/@alexfedoseev/isomorphic-

We're definitely not doing that. With react_on_rails, webpack is mainly generating a nice JavaScript file for inclusion into `application.js`. We're going to KISS. And that's all relative given how much there is to get right in an enterprise class web application.

## Upgrade

To upgrade existing apps to react on rails 7 see the [Installation Overview](docs/basics/installation-overview.md)

## Getting Started

**For more detailed instructions**, see the [React on Rails Basic Tutorial](docs/tutorial.md).
Expand Down Expand Up @@ -144,9 +148,9 @@ We're definitely not doing that. With react_on_rails, webpack is mainly generati
foreman start -f Procfile.dev
```

8. Visit [localhost:5000/hello_world](http://localhost:5000/hello_world). Note, `foreman` defaults to PORT 5000 unless you set the value of PORT in your environment. For example, you can `export PORT=3000` to use the Rails default port of 3000.
8. Visit [localhost:3000/hello_world](http://localhost:3000/hello_world). Note, `foreman` defaults to PORT 5000 unless you set the value of PORT in your environment. For example, you can `export PORT=3000` to use the Rails default port of 3000. For the hello_world example this is already set.

### Installation Summary
### Installation Overview

See the [Installation Overview](docs/basics/installation-overview.md) for a concise set summary of what's in a React on Rails installation.

Expand Down Expand Up @@ -222,7 +226,7 @@ In the following screenshot you can see the 3 parts of React on Rails rendering:
2. The wrapper div `<div id="HelloWorld-react-component-0">` specifies the div where to place the React rendering. It encloses the server-rendered HTML for the React component
3. Additional JavaScript is placed to console log any messages, such as server rendering errors. Note, these server side logs can be configured to only be sent to the server logs.

**Note**:
**Note**:

* If server rendering is not used (prerender: false), then the major difference is that the HTML rendered for the React component only contains the outer div: `<div id="HelloWorld-react-component-0"/>`. The first specification of the React component is just the same.
* The below image is not yet updated for version 7.0.0 which uses a `<script>` tag for the props. Instead of a hidden div, we have the props inside of the a `<script>` tag.
Expand Down
3 changes: 2 additions & 1 deletion docs/additional-reading/rspec-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ The following `config/react_on_rails.rb` settings **must** match your setup:
```ruby
# Directory where your generated assets go. All generated assets must go to the same directory.
# Configure this in your webpack config files. This relative to your Rails root directory.
config.generated_assets_dir = File.join(%w(app assets webpack))
# We recommend having different generated assets dirs per Rails env.
config.generated_assets_dir = File.join(%w[public webpack], Rails.env)

# Define the files we need to check for webpack compilation when running tests.
config.webpack_generated_files = %w( webpack-bundle.js )
Expand Down
11 changes: 7 additions & 4 deletions docs/basics/installation-overview.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Installation Overview

Here's an overview of installation if you're not using the generator.
Here's an overview of installation if you're not using the generator.

Note, the best way to understand how to use ReactOnRails is to study the examples:

Expand All @@ -9,23 +9,26 @@ Note, the best way to understand how to use ReactOnRails is to study the example

## Configure the `/client` Directory

This directory has no references to Rails outside of the destination directory for the files created by the various Webpack config files.
This directory has no references to Rails outside of the destination directory for the files created by the various Webpack config files.

The only requirements within this directory for basic React on Rails integration are:

1. Your webpack configuration files:
1. Create outputs in a directory like `/app/assets/webpack`, which is customizable in your `config/initializers/react_on_rails.rb`.
1. Create outputs in a directory like `/public/webpack`, which is customizable in your `config/initializers/react_on_rails.rb`.
1. Provide server rendering if you wish to use that feature.
1. Your JavaScript code "registers" any components and stores per the ReactOnRails APIs of ReactOnRails.register(components) and ReactOnRails.registerStore(stores). See API docs in [README.md](../../README.md) and the [ReactOnRails.js source](../../node_package/src/ReactOnRails.js).
1. Set your registration file as an "entry" point in your Webpack configs.
1. Add the [Manifest plugin](https://github.com/danethurber/webpack-manifest-plugin) to your config. For examples see [dummy config](../../spec/dummy/client/webpack.client.base.config.js).
The default path: `public/webpack` can be loaded with webpackConfigLoader as shown in the dummy example.
1. You create scripts in `client/package.json` per the example apps. These are used for building your Webpack assets. Also do this for your top level `package.json`.

## Rails Steps (outside of /client)
1. Add `gem "webpacker_lite"` to the Gemfile, run bundle. The gem provides the `stylesheet_pack_tag` and `javascript_pack_tag` helpers which is used to load the bundled assets to your layouts.[Dummy Example](../../spec/dummy/app/views/layouts/application.html.erb)
1. Configure the `config/initializers/react_on_rails.rb`. You can adjust some necessary settings and defaults. See file [spec/dummy/config/initializers/react_on_rails.rb](../../spec/dummy/config/initializers/react_on_rails.rb) for a detailed example of configuration, including comments on the different values to configure.
1. Configure your Procfiles per the example apps. These are at the root of your Rails installation.
1. Configure `config/initializers/assets.rb` probably like [spec/dummy/config/initializers/assets.rb](../../spec/dummy/config/initializers/assets.rb). This example shows what's necessary if you're enabling the hot-reloading Rails development option.
1. Configure your top level JavaScript files for inclusion in your layout. You'll want a version that you use for static assets, and you want a file for any files in your setup that are not part of your webpack build. The reason for this is for use with hot-reloading. If you are not using hot reloading, then you only need to configure your `application.js` file to include your Webpack generated files. For more information on hot reloading, see [Hot Reloading of Assets For Rails Development](../additional-reading/hot-reloading-rails-development.md)

1. Configure your `lib/tasks/assets.rake` file to run webpack during asset precompilation.
1. If you are deploying to Heroku, see [heroku-deployment.md](/docs/additional-reading/heroku-deployment.md)

Expand Down
35 changes: 11 additions & 24 deletions lib/generators/react_on_rails/base_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def update_git_ignore
node_modules

# Generated js bundles
/app/assets/webpack/*
/public/webpack/*
DATA

if dest_file_exists?(".gitignore")
Expand All @@ -37,26 +37,6 @@ def update_git_ignore
end
end

def update_application_js
data = <<-DATA.strip_heredoc
//= require webpack-bundle

DATA

app_js_path = "app/assets/javascripts/application.js"
found_app_js = dest_file_exists?(app_js_path) || dest_file_exists?("#{app_js_path}.coffee")
if found_app_js
prepend_to_file(found_app_js, data)
else
create_file(app_js_path, data)
end
end

def strip_application_js_of_double_blank_lines
application_js = File.join(destination_root, "app/assets/javascripts/application.js")
gsub_file(application_js, /^\n^\n/, "\n")
end

def create_react_directories
dirs = %w(components containers startup)
dirs.each { |name| empty_directory("client/app/bundles/HelloWorld/#{name}") }
Expand All @@ -65,6 +45,8 @@ def create_react_directories
def copy_base_files
base_path = "base/base/"
base_files = %w(app/controllers/hello_world_controller.rb
config/webpack/paths.yml
config/webpack/development.server.yml
client/.babelrc
client/webpack.config.js
client/REACT_ON_RAILS_CLIENT_README.md)
Expand All @@ -73,14 +55,15 @@ def copy_base_files

def template_base_files
base_path = "base/base/"
%w(config/initializers/react_on_rails.rb
%w(app/views/layouts/hello_world.html.erb
config/initializers/react_on_rails.rb
Procfile.dev
package.json
client/package.json).each { |file| template("#{base_path}#{file}.tt", file) }
end

def add_base_gems_to_gemfile
append_to_file("Gemfile", "\ngem 'mini_racer', platforms: :ruby\n")
append_to_file("Gemfile", "\ngem 'mini_racer', platforms: :ruby\ngem 'webpacker_lite'\n")
end

ASSETS_RB_APPEND = <<-DATA.strip_heredoc
Expand All @@ -93,7 +76,7 @@ def add_base_gems_to_gemfile
# Rails.application.config.assets.precompile += %w( server-bundle.js )

# Add folder with webpack generated assets to assets.paths
Rails.application.config.assets.paths << Rails.root.join("app", "assets", "webpack")
Rails.application.config.assets.paths << Rails.root.join("public", "webpack", Rails.env)
DATA

def append_to_assets_initializer
Expand Down Expand Up @@ -138,6 +121,10 @@ def print_helpful_message

What to do next:

- Include your webpack assets to your application layout.

<%= javascript_pack_tag 'main' %>

- Ensure your bundle and yarn installs of dependencies are up to date.

bundle && yarn
Expand Down
9 changes: 0 additions & 9 deletions lib/generators/react_on_rails/dev_tests_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,6 @@ def change_package_json_to_use_local_react_on_rails_module
File.open(package_json, "w+") { |f| f.puts new_contents }
end

def change_webpack_client_base_config_to_include_fallback
sentinel = /^\s\s},\n\s\splugins: \[\n/
config = File.join(destination_root, "client", "webpack.config.js")
old_contents = File.read(config)
new_contents = "const path = require('path');\n" +
old_contents.gsub(sentinel, FALLBACK_OPTION_FOR_NODE_MODULES)
File.open(config, "w+") { |f| f.puts new_contents }
end

def add_test_related_gems_to_gemfile
gem("rspec-rails", group: :test)
gem("capybara", group: :test)
Expand Down
23 changes: 23 additions & 0 deletions lib/generators/react_on_rails/templates/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
extends: eslint-config-shakacode

plugins:
- react

globals:
__DEBUG_SERVER_ERRORS__: true
__SERVER_ERRORS__: true

env:
browser: true
node: true
mocha: true

rules:
no-console: 0

# https://github.com/benmosher/eslint-plugin-import/issues/340
import/no-extraneous-dependencies: 0

# because template cannot find react-on-rails
import/no-unresolved: 0
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
web: rails s -p 3000
client: sh -c 'rm app/assets/webpack/* || true && cd client && bundle exec rake react_on_rails:locale && yarn run build:development'
client: sh -c 'rm -rf public/webpack/* || true && cd client && bundle exec rake react_on_rails:locale && yarn run build:development'
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
class HelloWorldController < ApplicationController
layout "hello_world"

def index
@hello_world_props = { name: "Stranger" }
end
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>ReactOnRailsWithWebpacker</title>
<%%= csrf_meta_tags %>

<%%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<%%= javascript_pack_tag 'main' %>
</head>

<body>
<%%= yield %>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
"npm": "4.1.1"
},
"scripts": {
"build:test": "webpack --config webpack.config.js",
"build:test": "NODE_ENV=test webpack --config webpack.config.js",
"build:production": "NODE_ENV=production webpack --config webpack.config.js",
"build:development": "webpack -w --config webpack.config.js"
"build:development": "NODE_ENV=development webpack -w --config webpack.config.js"
},
"cacheDirectories": ["node_modules", "client/node_modules"],
"dependencies": {
Expand All @@ -25,14 +25,16 @@
"es5-shim": "^4.5.9",
"expose-loader": "^0.7.3",
"imports-loader": "^0.7.1",
"js-yaml": "^3.8.2",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-on-rails": "<%= VersionSyntaxConverter.new.rubygem_to_npm %>",
<%- if options.redux? -%>
"react-redux": "^5.0.4",
"redux": "^3.6.0",
<%- end -%>
"webpack": "^2.3.3"
"webpack": "^2.3.3",
"webpack-manifest-plugin": "^1.1.0"
},
"devDependencies": {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,19 @@
"only-multiline"} ] */

const webpack = require('webpack');
const pathLib = require('path');
const { resolve } = require('path');
const ManifestPlugin = require('webpack-manifest-plugin');
const webpackConfigLoader = require('react-on-rails/webpackConfigLoader');

const devBuild = process.env.NODE_ENV !== 'production';
const configPath = resolve('..', 'config', 'webpack');
const { env, paths, publicPath } = webpackConfigLoader(configPath);

const devBuild = env !== 'production';

const config = {

context: resolve(__dirname),

entry: [
'es5-shim/es5-shim',
'es5-shim/es5-sham',
Expand All @@ -17,15 +25,19 @@ const config = {

output: {
filename: 'webpack-bundle.js',
path: pathLib.resolve(__dirname, '../app/assets/webpack'),
path: resolve('..', paths.output, paths.assets),
},

resolve: {
extensions: ['.js', '.jsx'],
},


plugins: [
new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }),
new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(env))),
new ManifestPlugin({ fileName: paths.manifest, publicPath, writeToFileEmit: true }),
],

module: {
rules: [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ ReactOnRails.configure do |config|

# Directory where your generated assets go. All generated assets must go to the same directory.
# Configure this in your webpack config files. This relative to your Rails root directory.
config.generated_assets_dir = File.join(%w(app assets webpack))
config.generated_assets_dir = File.join(%w[public webpack], Rails.env)

# Define the files we need to check for webpack compilation when running tests.
config.webpack_generated_files = %w( webpack-bundle.js )
Expand Down Expand Up @@ -82,9 +82,8 @@ ReactOnRails.configure do |config|
config.server_render_method = "ExecJS"
<%- end -%>

# Client js uses assets not digested by rails.
# For any asset matching this regex, non-digested symlink will be created (what webpack's css wants)
# To disable symlinks set this parameter to nil.
config.symlink_non_digested_assets_regex = /\.(png|jpg|jpeg|gif|tiff|woff|ttf|eot|svg|map)/

# If you want to use webpack for CSS and images, and still use the asset pipeline,
# see https://github.com/shakacode/react_on_rails/blob/master/docs/additional-reading/rails-assets.md
# And you will use a setting like this.
# config.symlink_non_digested_assets_regex = /\.(png|jpg|jpeg|gif|tiff|woff|ttf|eot|svg|map)/
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
default: &default
enabled: false
host: localhost
port: 3500

development:
<<: *default
# set to true of you want hot loading as default
enabled: false
Loading