react_on_rails 11.0.3 → 12.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (129) hide show
  1. checksums.yaml +5 -5
  2. data/.circleci/config.yml +320 -0
  3. data/.eslintignore +2 -1
  4. data/.eslintrc +30 -2
  5. data/.github/FUNDING.yml +1 -0
  6. data/.gitignore +3 -1
  7. data/.prettierignore +10 -0
  8. data/.prettierrc +23 -0
  9. data/.release-it.json +3 -0
  10. data/.rubocop.yml +39 -11
  11. data/.travis.yml +11 -22
  12. data/CHANGELOG.md +209 -4
  13. data/CONTRIBUTING.md +64 -84
  14. data/Gemfile +3 -5
  15. data/KUDOS.md +4 -1
  16. data/{docs/LICENSE.md → LICENSE.md} +1 -1
  17. data/PROJECTS.md +7 -1
  18. data/REACT-ON-RAILS-PRO-LICENSE +95 -0
  19. data/README.md +233 -634
  20. data/Rakefile +1 -5
  21. data/SUMMARY.md +42 -29
  22. data/book.json +5 -5
  23. data/docs/additional-reading/asset-pipeline.md +8 -16
  24. data/docs/additional-reading/convert-rails-5-api-only-app.md +19 -0
  25. data/docs/additional-reading/credits.md +10 -0
  26. data/docs/additional-reading/images.md +1 -1
  27. data/docs/additional-reading/rails-engine-integration.md +7 -0
  28. data/docs/additional-reading/rails_view_rendering_from_inline_javascript.md +2 -1
  29. data/docs/additional-reading/react-helmet.md +30 -10
  30. data/docs/additional-reading/react-router.md +52 -75
  31. data/docs/additional-reading/server-rendering-tips.md +14 -11
  32. data/docs/additional-reading/upgrade-webpacker-v3-to-v4.md +10 -0
  33. data/docs/additional-reading/webpack.md +2 -2
  34. data/docs/api/javascript-api.md +24 -4
  35. data/docs/api/redux-store-api.md +102 -0
  36. data/docs/api/view-helpers-api.md +133 -0
  37. data/docs/articles.md +20 -0
  38. data/docs/basics/client-vs-server-rendering.md +23 -0
  39. data/docs/basics/configuration.md +145 -61
  40. data/docs/basics/deployment.md +4 -0
  41. data/docs/basics/{generator.md → generator-details.md} +5 -8
  42. data/docs/basics/heroku-deployment.md +24 -0
  43. data/docs/basics/hmr-and-hot-reloading-with-the-webpack-dev-server.md +49 -0
  44. data/docs/basics/i18n.md +45 -23
  45. data/docs/basics/installation-into-an-existing-rails-app.md +59 -0
  46. data/docs/basics/minitest-configuration.md +31 -0
  47. data/docs/basics/react-server-rendering.md +29 -0
  48. data/docs/{additional-reading → basics}/recommended-project-structure.md +38 -10
  49. data/docs/basics/render-functions-and-railscontext.md +205 -0
  50. data/docs/basics/rspec-configuration.md +73 -0
  51. data/docs/basics/upgrading-react-on-rails.md +74 -3
  52. data/docs/basics/webpack-configuration.md +50 -0
  53. data/docs/contributor-info/errors-with-hooks.md +45 -0
  54. data/docs/contributor-info/pull-requests.md +44 -0
  55. data/docs/misc/doctrine.md +2 -2
  56. data/docs/{additional-reading → outdated}/code-splitting.md +19 -9
  57. data/docs/outdated/how-react-on-rails-works.md +44 -0
  58. data/docs/{basics/installation-overview.md → outdated/manual-installation-overview.md} +8 -13
  59. data/docs/{additional-reading → outdated}/rails-assets-relative-paths.md +3 -3
  60. data/docs/{additional-reading → outdated}/rails-assets.md +5 -13
  61. data/docs/testimonials/hvmn.md +25 -0
  62. data/docs/testimonials/resortpass.md +13 -0
  63. data/docs/testimonials/testimonials.md +28 -0
  64. data/docs/tutorial.md +182 -44
  65. data/jest.config.js +4 -0
  66. data/lib/generators/USAGE +1 -1
  67. data/lib/generators/react_on_rails/base_generator.rb +2 -2
  68. data/lib/generators/react_on_rails/dev_tests_generator.rb +3 -2
  69. data/lib/generators/react_on_rails/generator_helper.rb +4 -6
  70. data/lib/generators/react_on_rails/install_generator.rb +2 -0
  71. data/lib/generators/react_on_rails/templates/base/base/Procfile.dev +3 -1
  72. data/lib/generators/react_on_rails/templates/base/base/Procfile.dev-hmr +26 -0
  73. data/lib/generators/react_on_rails/templates/base/base/app/javascript/bundles/HelloWorld/components/HelloWorld.jsx +20 -40
  74. data/lib/generators/react_on_rails/templates/base/base/config/initializers/react_on_rails.rb +4 -1
  75. data/lib/generators/react_on_rails/templates/redux/base/app/javascript/bundles/HelloWorld/components/HelloWorld.jsx +4 -8
  76. data/lib/generators/react_on_rails/templates/redux/base/app/javascript/bundles/HelloWorld/store/helloWorldStore.js +1 -3
  77. data/lib/react_on_rails/configuration.rb +171 -100
  78. data/lib/react_on_rails/error.rb +2 -0
  79. data/lib/react_on_rails/git_utils.rb +2 -0
  80. data/lib/react_on_rails/{react_on_rails_helper.rb → helper.rb} +133 -161
  81. data/lib/react_on_rails/json_output.rb +1 -1
  82. data/lib/react_on_rails/json_parse_error.rb +28 -0
  83. data/lib/react_on_rails/locales/base.rb +150 -0
  84. data/lib/react_on_rails/locales/to_js.rb +37 -0
  85. data/lib/react_on_rails/locales/to_json.rb +27 -0
  86. data/lib/react_on_rails/prerender_error.rb +56 -18
  87. data/lib/react_on_rails/react_component/render_options.rb +31 -3
  88. data/lib/react_on_rails/server_rendering_js_code.rb +42 -0
  89. data/lib/react_on_rails/server_rendering_pool/ruby_embedded_java_script.rb +93 -63
  90. data/lib/react_on_rails/server_rendering_pool.rb +1 -16
  91. data/lib/react_on_rails/test_helper/ensure_assets_compiled.rb +7 -8
  92. data/lib/react_on_rails/test_helper/webpack_assets_compiler.rb +17 -0
  93. data/lib/react_on_rails/test_helper/webpack_assets_status_checker.rb +10 -6
  94. data/lib/react_on_rails/test_helper.rb +18 -7
  95. data/lib/react_on_rails/utils.rb +65 -25
  96. data/lib/react_on_rails/version.rb +1 -1
  97. data/lib/react_on_rails/version_checker.rb +5 -1
  98. data/lib/react_on_rails/version_syntax_converter.rb +14 -12
  99. data/lib/react_on_rails/webpacker_utils.rb +44 -10
  100. data/lib/react_on_rails.rb +7 -2
  101. data/lib/tasks/assets.rake +33 -46
  102. data/lib/tasks/locale.rake +4 -2
  103. data/package-scripts.yml +49 -0
  104. data/package.json +49 -40
  105. data/rakelib/dummy_apps.rake +1 -9
  106. data/rakelib/example_type.rb +3 -1
  107. data/rakelib/examples.rake +3 -0
  108. data/rakelib/lint.rake +2 -7
  109. data/rakelib/node_package.rake +2 -2
  110. data/rakelib/release.rake +4 -8
  111. data/rakelib/run_rspec.rake +5 -18
  112. data/react_on_rails.gemspec +5 -6
  113. data/tsconfig.json +14 -0
  114. data/webpackConfigLoader.js +5 -4
  115. data/yarn.lock +7645 -1821
  116. metadata +70 -60
  117. data/Gemfile.rails32 +0 -74
  118. data/docs/additional-reading/babel.md +0 -5
  119. data/docs/additional-reading/caching-and-performance.md +0 -4
  120. data/docs/additional-reading/heroku-deployment.md +0 -92
  121. data/docs/additional-reading/hot-reloading-rails-development.md +0 -57
  122. data/docs/additional-reading/node-server-rendering.md +0 -5
  123. data/docs/additional-reading/rspec-configuration.md +0 -56
  124. data/docs/api/ruby-api-hot-reload-view-helpers.md +0 -44
  125. data/docs/api/ruby-api.md +0 -8
  126. data/lib/generators/react_on_rails/templates/base/base/Procfile.dev-server +0 -12
  127. data/lib/react_on_rails/assets_precompile.rb +0 -150
  128. data/lib/react_on_rails/locales_to_js.rb +0 -134
  129. /data/docs/{misc → outdated}/rails3.md +0 -0
@@ -0,0 +1,49 @@
1
+ # HMR and Hot Reloading with the webpack-dev-server
2
+
3
+ The webpack-dev-server provides:
4
+
5
+ 1. Speedy compilation of client side assets
6
+ 2. Optional HMR which means that the page will reload automatically when after
7
+ compilation completes. Note, some developers do not like this, as you'll
8
+ abruptly lose any tweaks within the Chrome development tools.
9
+ 3. Optional hot-reloading. The older react-hot-loader has been deprecated in
10
+ favor of [fast-refresh](https://reactnative.dev/docs/fast-refresh).
11
+ For use with webpack, see [react-refresh-webpack-plugin](https://github.com/pmmmwh/react-refresh-webpack-plugin).
12
+
13
+ If you are ***not*** using server-side rendering (***not*** using `prerender: true`),
14
+ then you can follow all the regular docs for using the `bin/webpack-dev-server`
15
+ during development.
16
+
17
+
18
+ # Server Side Rendering with the Default rails/webpacker bin/webpack-dev-server
19
+
20
+ If you are using server-side rendering, then you have a couple options. The
21
+ recommended technique is to have a different webpack configuration for server
22
+ rendering.
23
+
24
+
25
+
26
+
27
+ ## If you use the same Webpack setup for your server and client bundles
28
+ If you do use the webpack-dev-server for prerendering, be sure to set the
29
+ `config/initializers/react_on_rails.rb` setting of
30
+
31
+ ```
32
+ config.same_bundle_for_client_and_server = true
33
+ ```
34
+
35
+ `dev_server.hmr` maps to [devServer.hot](https://webpack.js.org/configuration/dev-server/#devserverhot).
36
+ This must be false if you're using the webpack-dev-server for client and server bundles.
37
+
38
+ `dev_server.inline` maps to [devServer.inline](https://webpack.js.org/configuration/dev-server/#devserverinline).
39
+ This must also be false.
40
+
41
+ If you don't configure these two to false, you'll see errors like:
42
+
43
+ * "ReferenceError: window is not defined" (if hmr is true)
44
+ * "TypeError: Cannot read property 'prototype' of undefined" (if inline is true)
45
+
46
+
47
+
48
+
49
+
data/docs/basics/i18n.md CHANGED
@@ -1,23 +1,10 @@
1
- # How to add I18n
1
+ # I18n
2
2
 
3
3
  Here's a summary of adding the I18n functionality.
4
4
 
5
- You can refer to [react-webpack-rails-tutorial](https://github.com/shakacode/react-webpack-rails-tutorial) and [PR #340](https://github.com/shakacode/react-webpack-rails-tutorial/pull/340), [commmited](https://github.com/shakacode/react-webpack-rails-tutorial/commit/ef369ed9d922aea5116ca7e50208169fd7831389) for a complete example.
5
+ 1. Add `config.i18n_dir` in `config/initializers/react_on_rails.rb`
6
6
 
7
- 1. Add `react-intl` & `intl` to `client/package.json`, and remember to `bundle && yarn install`.
8
-
9
- ```js
10
- "dependencies": {
11
- ...
12
- "intl": "^1.2.5",
13
- "react-intl": "^2.1.5",
14
- ...
15
- }
16
- ```
17
-
18
- 2. Add `config.i18n_dir` in `config/initializers/react_on_rails.rb`
19
-
20
- `react-intl` requires locale files in json format. React on Rails will generate `translations.js` & `default.js` automatically after you configured your `config.i18n_dir` in `config/initializers/react_on_rails.rb`.
7
+ React on Rails will generate `translations.json` & `default.json` automatically (see #3) after you configured your `config.i18n_dir` in `config/initializers/react_on_rails.rb`.
21
8
 
22
9
  ```ruby
23
10
  # Replace the following line to the location where you keep translation.js & default.js.
@@ -31,16 +18,50 @@ You can refer to [react-webpack-rails-tutorial](https://github.com/shakacode/rea
31
18
  config.i18n_yml_dir = Rails.root.join("PATH_TO", "YOUR_YAML_I18N_FOLDER")
32
19
  ```
33
20
 
34
- `translations.js`: All your locales in json format.
35
- `default.js`: Default settings in json format.
21
+ `translations.json`: All your locales in json format.
22
+ `default.json`: Default settings in json format.
36
23
 
37
- 3. Add `translations.js` and `default.js` to your `.gitignore` and `.eslintignore`.
24
+ 2. Add `translations.json` and `default.json` to your `.gitignore`.
25
+
26
+ 3. Javascript locale files must be generated before `yarn build`.
38
27
 
39
- 4. Javascript locale files must be generated before `yarn build`.
28
+ Once you setup `config.i18n_dir` as in the previous step, you will need to make sure `rake react_on_rails:locale` runs before webpack.
29
+
30
+ For development, you should adjust your startup scripts (Procfiles) so that they run **`bundle exec rake react_on_rails:locale`** before running any webpack watch process (`yarn run build:development`).
31
+
32
+ You may need to configure your CI to run **`bundle exec rake react_on_rails:locale`** before any webpack process if you are not using the React on Rails test helper.
33
+
34
+ Note, if you are try to lint before running tests, and you are depending on the test helper to build your locales, your linting will fail because the translations won't be built yet.
35
+
36
+ The fix is either to
37
+ 1) run the rake task to build the translations before running the lint command or
38
+ 2) to run the tests first.
40
39
 
41
- Once you setup `config.i18n_dir` as in the previous step, react_on_rails will automatically do this for testing (if using the `ReactOnRails::TestHelper.configure_rspec_to_compile_assets` and for production deployments if using the [default precompile rake hook](../additional-reading/heroku-deployment.md). For development, you should adjust your startup scripts (Procfiles) so that they run **`bundle exec rake react_on_rails:locale`** before running any webpack watch process (`yarn run build:development`). You may need to configure your CI to run **`bundle exec rake react_on_rails:locale`** before any webpack process if you are not using the React on Rails test helper. Note, if you are try to lint before running tests, and you are depending on the test helper to build your locales, your linting will fail because the translations won't be built yet. The fix is either to 1) run the rake task to build the translations before running the lint command or 2) to run the tests first.
40
+ # Generate locales with react-intl support
42
41
 
43
- 5. In React, you need to initialize `react-intl`, and set parameters for it.
42
+ By default the locales generated in json format. If you need to generate files in the prior way
43
+ with `react-intl` supported via js files:
44
+
45
+ 1. Specify i18n output format in `react_on_rails.rb`:
46
+ ```rb
47
+ config.i18n_output_format = 'js'
48
+ ```
49
+
50
+ 2. Add `react-intl` & `intl` to `client/package.json`, and remember to `bundle && yarn install`.
51
+ Versions should be newer than these:
52
+
53
+ ```js
54
+ "dependencies": {
55
+ ...
56
+ "intl": "^1.2.5",
57
+ "react-intl": "^2.1.5",
58
+ ...
59
+ }
60
+ ```
61
+
62
+ 3. Add `translations.js` and `default.js` to your `.gitignore` and `.eslintignore`.
63
+
64
+ 4. In React, you need to initialize `react-intl`, and set parameters for it.
44
65
 
45
66
  ```js
46
67
  ...
@@ -73,5 +94,6 @@ You can refer to [react-webpack-rails-tutorial](https://github.com/shakacode/rea
73
94
  ```
74
95
 
75
96
  # Notes
76
-
97
+ * See why using JSON could be better compare to JS if amount of data is hure [ https://v8.dev/blog/cost-of-javascript-2019#json]( https://v8.dev/blog/cost-of-javascript-2019#json).
77
98
  * See [Support for Rails' i18n pluralization #1000](https://github.com/shakacode/react_on_rails/issues/1000) for a discussion of issues around pluralization.
99
+ * *Outdated:* You can refer to [react-webpack-rails-tutorial](https://github.com/shakacode/react-webpack-rails-tutorial) and [PR #340](https://github.com/shakacode/react-webpack-rails-tutorial/pull/340), [commmited](https://github.com/shakacode/react-webpack-rails-tutorial/commit/ef369ed9d922aea5116ca7e50208169fd7831389) for a complete example.
@@ -0,0 +1,59 @@
1
+ # Getting Started with an existing Rails app
2
+
3
+ **Also consult the instructions for installing on a fresh Rails app**, see the [React on Rails Basic Tutorial](../../docs/tutorial.md).
4
+
5
+ **If you have rails-5 API only project**, first [convert the rails-5 API only app to rails app](#convert-rails-5-api-only-app-to-rails-app) before [getting started](#getting-started-with-an-existing-rails-app).
6
+
7
+ 1. Add the following to your Gemfile and `bundle install`. We recommend fixing the version of React on Rails, as you will need to keep the exact version in sync with the version in your `client/package.json` file.
8
+
9
+ ```ruby
10
+ gem "react_on_rails", "12.0.0" # Update to the current version
11
+ gem "webpacker", "~> 5"
12
+ ```
13
+
14
+ 2. Run the following 2 commands to install Webpacker with React. Note, if you are using an older version of Rails than 5.1, you'll need to install webpacker with React per the instructions [here](https://github.com/rails/webpacker).
15
+
16
+
17
+ ```bash
18
+ $ bundle exec rails webpacker:install
19
+ $ bundle exec rails webpacker:install:react
20
+ ```
21
+
22
+ 3. Commit this to git (or else you cannot run the generator unless you pass the option `--ignore-warnings`).
23
+
24
+ 4. See help for the generator:
25
+
26
+ ```bash
27
+ $ rails generate react_on_rails:install --help
28
+ ```
29
+
30
+ 5. Run the generator with a simple "Hello World" example (more options below):
31
+
32
+ ```bash
33
+ $ rails generate react_on_rails:install
34
+ ```
35
+
36
+ 6. Ensure that you have `foreman` installed: `gem install foreman`.
37
+
38
+ 7. Start your Rails server:
39
+
40
+ ```bash
41
+ $ foreman start -f Procfile.dev
42
+ ```
43
+
44
+ 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.
45
+
46
+ ## Installation
47
+
48
+ See the [Installation Overview](docs/outdated/manual-installation-overview.md) for a concise set summary of what's in a React on Rails installation.
49
+
50
+
51
+ ## NPM
52
+
53
+ All JavaScript in React On Rails is loaded from npm: [react-on-rails](https://www.npmjs.com/package/react-on-rails). To manually install this (you did not use the generator), assuming you have a standard configuration, run this command (assuming you are in the directory where you have your `node_modules`):
54
+
55
+ ```bash
56
+ $ yarn add react-on-rails --exact
57
+ ```
58
+
59
+ That will install the latest version and update your package.json. **NOTE:** the `--exact` flag will ensure that you do not have a "~" or "^" for your react-on-rails version in your package.json.
@@ -0,0 +1,31 @@
1
+ # Minitest Configuration
2
+
3
+ The setup for minitest is the same as for rspec with the following difference.
4
+
5
+ Rather than calling `ReactOnRails::TestHelper.configure_rspec_to_compile_assets(config)`, instead you will do something like this:
6
+
7
+ ```ruby
8
+ class ActiveSupport::TestCase
9
+ setup do
10
+ ReactOnRails::TestHelper.ensure_assets_compiled
11
+ end
12
+ end
13
+ ```
14
+
15
+
16
+ Or maybe something like this, from the [minitest docs](https://github.com/seattlerb/minitest/blob/master/lib/minitest/test.rb#L119):
17
+
18
+ ```ruby
19
+ module MyMinitestPlugin
20
+ def before_setup
21
+ super
22
+ ReactOnRails::TestHelper.ensure_assets_compiled
23
+ end
24
+ end
25
+
26
+ class MiniTest::Test
27
+ include MyMinitestPlugin
28
+ end
29
+ ```
30
+
31
+
@@ -0,0 +1,29 @@
1
+ # React Server Rendering
2
+
3
+ See also [Client vs. Server Rendering](./client-vs-server-rendering.md)
4
+
5
+ ## What is Server Rendering?
6
+
7
+ Here's a [decent article to introduce you to server rendering](https://medium.freecodecamp.org/server-side-rendering-your-react-app-in-three-simple-steps-7a82b95db82e). Note, React on Rails takes care of calling the methods in [ReactDOMServer](https://reactjs.org/docs/react-dom-server.html).
8
+
9
+ During the Rails rendering of HTML per a browser request, the Rails server will execute some JavaScript to create a string of HTML used for React server rendering. This resulting HTML is placed with in your Rails view's output.
10
+
11
+ The default JavaScript interpretter is [ExecJS](https://github.com/rails/execjs). If you want to maximize the perfomance of your server rendering, then you want to use React on Rails Pro which uses NodeJS to do the server rendering. See the [docs for React on Rails Pro](https://github.com/shakacode/react_on_rails/wiki).
12
+
13
+ See [this note](docs/outdated/how-react-on-rails-works.md#client-side-rendering-vs-server-side-rendering)
14
+
15
+
16
+ ## How do you do Server Rendering with React on Rails?
17
+ 1. The `react_component` view helper method provides the `prerender:` option to switch on or off server rendering.
18
+ 1. Configure your Webpack setup to create a different server bundle per your needs. While you may reuse the same bundle as for client rendering, this is not common in larger apps for many reasons, such as as code splitting, handling CSS and images, different code paths for React Router on the server vs. client, etc.
19
+ 1. You need to configure `config.server_bundle_js_file = "my-server-bundle.js"` in your `config/initializers/react_on_rails.rb`
20
+
21
+ ## Do you need server rendering?
22
+
23
+ Server rendering is used for either SEO or performance reasons.
24
+
25
+ ## Considerations for what code can run on in server rendering
26
+
27
+ 1. Never access `window`. Animations, globals on window, etc. just don't make sense when you're trying to run some JavaScript code to output a string of HTML.
28
+ 2. JavaScript calls to `setTimeout`, `setInterval`, and `clearInterval` similarly don't make sense when server rendering.
29
+ 3. Promises don't work when server rendering. Anything to be done in a promise will never complete. This includes concepts such as asynchronous code loading and AJAX calls. If you want to do server rendering with asynchronous calls, [get in touch](mailto:justin@shakacode.com) as we're working on a Node renderer that handles asynchronous calls.
@@ -1,8 +1,41 @@
1
- # Project structure
1
+ # Recommended Project structure
2
2
 
3
- While React On Rails does not *enforce* a specific project structure, we do *recommend* a standard organization. The more we follow standards as a community, the easier it will be for all of us to move between various Rails projects that include React On Rails.
3
+ The React on Rails generator uses the standard `rails/webpacker` convention of this structure:
4
+
5
+ ```yml
6
+ app/javascript:
7
+ ├── bundles:
8
+ │ # Logical groups of files that can be used for code splitting
9
+ │ └── hello-world-bundle.js
10
+ ├── packs:
11
+ │ # only webpack entry files here
12
+ │ └── hello-world-bundle.js
13
+ ```
14
+
15
+ However, you may wish to move all your client side files to a single directory called something like `/client`.
16
+
17
+ ## Steps to convert from the generator defaults to use a `/client` directory structure.
18
+
19
+ 1. Move the directory:
20
+
21
+ ```
22
+ mv app/javascript client
23
+ ```
24
+
25
+ 2. Edit your `/config/webpacker.yml` file. Change the `default/source_path`:
26
+
27
+ ```yml
28
+ source_path: client
29
+ ```
30
+
31
+ ## Moving node_modules from `/` to `/client` with a custom webpack setup.
32
+
33
+ `rails/webpacker` probably doesn't support having your main node_modules directory under `/client`, so only follow these steps if you want to use your own webpack configuration.
34
+
35
+ 1. Move the `/package.json` to `/client/package.json`
36
+ 2. Create a `/package.json` that delegates to `/client/package.json`. See the example in [spec/dummy/package.json](../../spec/dummy/package.json).
37
+ 3. See the webpack configuration in [spec/dummy/client](../../spec/dummy/client) for a webpack configuration example.
4
38
 
5
- The best way to understand these standards is to follow this example: [github.com/shakacode/react-webpack-rails-tutorial](https://github.com/shakacode/react-webpack-rails-tutorial)
6
39
 
7
40
  ## JavaScript Assets
8
41
  1. `/client`: All client side JavaScript goes under the `/client` directory. Place all the major domains of the client side app under client.
@@ -10,7 +43,7 @@ The best way to understand these standards is to follow this example: [github.co
10
43
  1. `/client/app/bundles`: Top level of different app domains. Use a name within this directory for you app domains. For example, if you had a domain called `widget-editing`, then you would have: `/client/app/bundles/widget-editing`
11
44
  1. `/client/app/lib`: Common code for bundles
12
45
  1. Within each bundle directory (or the lib directory), such as a domain named "comments"
13
- `/client/app/bundles/comments`, use following directory structure:
46
+ `/client/app/bundles/comments`, use following directory structure, if you're using redux. However, with React hooks, this will probably be a bit different:
14
47
 
15
48
  * `/actions`: Redux actions.
16
49
  * `/components`: "dumb" components (no connections to Redux or Ajax). These get props and can render themselves and children.
@@ -32,7 +65,7 @@ This isn't really any technique, as you keep handling all your styling assets us
32
65
  1. Much simpler! There's no changes really from your current processes.
33
66
 
34
67
  ### Using Webpack to Manage Styling Assets
35
- This technique involves customization of the webpack config files to generate CSS, image, and font assets. See [webpack.client.rails.build.config.js](https://github.com/shakacode/react_on_rails/blob/master/spec%2Fdummy%2Fclient%2Fwebpack.client.rails.build.config.js) for an example how to set the webpack part.
68
+ This technique involves customization of the webpack config files to generate CSS, image, and font assets.
36
69
 
37
70
  #### Directory structure
38
71
  1. `/client/app/assets`: Assets for CSS for client app.
@@ -42,8 +75,3 @@ This technique involves customization of the webpack config files to generate CS
42
75
  1. You can use [CSS modules](https://github.com/css-modules/css-modules), which is super compelling once you seen the benefits.
43
76
  1. You can do hot reloading of your assets. Thus, you do not have to refresh your web page to see asset change, including changing styles.
44
77
  1. You can run your client code on a mocked out express server for super fast prototyping. In other words, your client application can somewhat more easily be move to a different application server.
45
-
46
- #### Updates 2017-03-04 Regarding CSS handled by Webpack
47
- * See article [Best practices for CSS and CSS Modules using Webpack](https://forum.shakacode.com/t/best-practices-for-css-and-css-modules-using-webpack/799).
48
- * In the near future, all docs will be updated to Webpack v2 and probably recommended to move all CSS handling to Webpack v2 for advanced users. In the near term, global CSS handled by Rails will be best for simple projects. Another data point is that Rails is moving in direction of handling JavaScript, but not CSS, with [Webpacker](https://github.com/rails/webpacker).
49
-
@@ -0,0 +1,205 @@
1
+ # Render-Functions and the Rails Context
2
+
3
+ ## Render-Functions
4
+
5
+ When you use a render-function to create react components (or renderedHtml on the server), or you
6
+ used shared redux stores, you get two params passed to your function that creates a React component:
7
+
8
+ 1. `props`: Props that you pass in the view helper of either `react_component` or `redux_store`
9
+ 2. `railsContext`: Rails contextual information, such as the current pathname. You can customize
10
+ this in your config file. **Note**: The `railsContext` is not related to the concept of a
11
+ ["context" for React components](https://facebook.github.io/react/docs/context.html#how-to-use-context).
12
+
13
+ These parameters (`props` and `railsContext`) will be the same regardless of either client or server
14
+ side rendering, except for the key `serverSide` based on whether or not you are server rendering.
15
+
16
+ While you could manually configure your Rails code to pass the "`railsContext` information" with
17
+ the rest of your "props", the `railsContext` is a convenience because it's passed consistently to
18
+ all invocations of render functions.
19
+
20
+ For example, suppose you create a "render-function" called MyAppComponent.
21
+
22
+ ```js
23
+ import React from 'react';
24
+ const MyAppComponent = (props, railsContext) => (
25
+ // NOTE: need to wrap in a function so this is proper React function component that can use
26
+ // hooks
27
+
28
+ // the props get passed again, but we ignore since we use a closure
29
+ // or should we
30
+ () =>
31
+ <div>
32
+ <p>props are: {JSON.stringify(props)}</p>
33
+ <p>railsContext is: {JSON.stringify(railsContext)}
34
+ </p>
35
+ </div>
36
+ );
37
+ export default MyAppComponent;
38
+ ```
39
+
40
+ ------------------------------
41
+
42
+ _This would be alternate API where you have to call React.createElement and the React on Rails code doesn't do that._
43
+
44
+ ```js
45
+ import React from 'react';
46
+ const MyAppComponent = (props, railsContext) => (
47
+ // NOTE: need to wrap in a function so this is proper React function component that can use
48
+ // hooks
49
+ React.createElement(
50
+ () =>
51
+ <div>
52
+ <p>props are: {JSON.stringify(props)}</p>
53
+ <p>railsContext is: {JSON.stringify(railsContext)}
54
+ </p>
55
+ </div>,
56
+ props)
57
+ );
58
+ export default MyAppComponent;
59
+ ```
60
+
61
+ ------------------------------------
62
+
63
+ *Note: you will get a React browser console warning if you try to serverRender this since the value of `serverSide` will be different for server rendering.*
64
+
65
+ So if you register your render-function `MyAppComponent`, it will get called like:
66
+
67
+ ```js
68
+ reactComponent = MyAppComponent(props, railsContext);
69
+ ```
70
+
71
+ and, similarly, any redux store is always initialized with 2 parameters:
72
+
73
+ ```js
74
+ reduxStore = MyReduxStore(props, railsContext);
75
+ ```
76
+
77
+ Note: you never make these calls. React on Rails makes these calls when it does either client or server rendering. You will define functions that take these 2 params and return a React component or a Redux Store. Naturally, you do not have to use second parameter of the railsContext if you do not need it. If you don't take a second parameter, then you're probably defining a React function component and you will simply return a React Element, often just JSX.
78
+
79
+ (Note: see below [section](#multiple-react-components-on-a-page-with-one-store) on how to setup redux stores that allow multiple components to talk to the same store.)
80
+
81
+ The `railsContext` has: (see implementation in file [ReactOnRails::Helper](https://github.com/shakacode/react_on_rails/tree/master/lib/react_on_rails/helper.rb), method `rails_context` for the definitive list).
82
+
83
+ ```ruby
84
+ {
85
+ railsEnv: Rails.env
86
+ inMailer: in_mailer?,
87
+ # Locale settings
88
+ i18nLocale: I18n.locale,
89
+ i18nDefaultLocale: I18n.default_locale,
90
+ rorVersion: ReactOnRails::VERSION,
91
+ rorPro: ReactOnRails::Utils.react_on_rails_pro?
92
+
93
+ # URL settings
94
+ href: request.original_url,
95
+ location: "#{uri.path}#{uri.query.present? ? "?#{uri.query}": ""}",
96
+ scheme: uri.scheme, # http
97
+ host: uri.host, # foo.com
98
+ port: uri.port,
99
+ pathname: uri.path, # /posts
100
+ search: uri.query, # id=30&limit=5
101
+ httpAcceptLanguage: request.env["HTTP_ACCEPT_LANGUAGE"]
102
+
103
+ # Other
104
+ serverSide: boolean # Are we being called on the server or client? Note: if you conditionally
105
+ # render something different on the server than the client, then React will only show the
106
+ # server version!
107
+ }
108
+ ```
109
+
110
+ Plus, you can add your customizations to this. See "rendering extension" below.
111
+
112
+ ## Rails Context
113
+
114
+ The `railsContext` is a second param passed to your render-functions for React components. This is in addition to the props that are passed from the `react_component` Rails helper. For example:
115
+
116
+ ERB view file:
117
+
118
+ ```ruby
119
+ # Rails View
120
+ <%= react_component("HelloWorld", props: { name: "Stranger" }) %>
121
+ ```
122
+
123
+ This is what your HelloWorld.js file might contain. The railsContext is always available for any parameters that you _always_ want available for your React components. It has _nothing_ to do with the concept of the [React Context](https://reactjs.org/docs/context.html).
124
+
125
+ ```js
126
+ import React from 'react';
127
+
128
+ export default (props, railsContext) => {
129
+ // Note, wrap in a function so this is React function component
130
+ return () => (
131
+ <div>
132
+ Your locale is {railsContext.i18nLocale}.<br/>
133
+ Hello, {props.name}!
134
+ </div>
135
+ );
136
+ };
137
+ ```
138
+
139
+ ## Why is the railsContext only passed to render-functions?
140
+
141
+ There's no reason that the railsContext would ever get passed to your React component unless the value is explicitly put into the props used for rendering. If you create a react component, rather than a render-function, for use by React on Rails, then you get whatever props are passed in from the view helper, which **does not include the Rails Context**. It's trivial to wrap your component in a "render-function" to return a new component that takes both:
142
+
143
+ ```js
144
+ import React from 'react';
145
+ import AppComponent from './AppComponent';
146
+ const AppComponentWithRailsContext = (props, railsContext) => (
147
+ // Create a React Function Component so you can
148
+ // use the React Hooks API in this React Function Component
149
+ () => <AppComponent {...{...props, railsContext}}/>
150
+ )
151
+ export default AppComponentWithRailsContext;
152
+ ```
153
+
154
+ Consider this line in depth:
155
+
156
+ ```js
157
+ <AppComponent {...{ ...props, railsContext }}/>
158
+ ```
159
+
160
+ The outer `{...` is for the [JSX spread operator for attributes](https://facebook.github.io/react/docs/jsx-in-depth.html#spread-attributes) and the innner `{...` is for the [Spread in object literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Spread_in_object_literals).
161
+
162
+ ## Use Cases
163
+
164
+ ### Heroku Preboot Considerations
165
+
166
+ [Heroku Preboot](https://devcenter.heroku.com/articles/preboot) is a feature on Heroku that allows for faster deploy times. When you promote your staging app to production, Preboot simply switches the production server to point at the staging app's container. This means it can deploy much faster since it doesn't have to rebuild anything. However, this means that if you use the [Define Plugin](https://github.com/webpack/docs/wiki/list-of-plugins#defineplugin) to provide the rails environment to your client code as a variable, that variable will erroneously still have a value of `Staging` instead of `Production`. The `Rails.env` provided at runtime in the railsContext is, however, accurate.
167
+
168
+ ### Needing the current URL path for server rendering
169
+
170
+ Suppose you want to display a nav bar with the current navigation link highlighted by the URL. When you server-render the code, your code will need to know the current URL/path. The new `railsContext` has this information. Your application will apply something like an "active" class on the server rendering.
171
+
172
+ ### Configuring different code for server side rendering
173
+
174
+ Suppose you want to turn off animation when doing server side rendering. The `serverSide` value is just what you need.
175
+
176
+ ## Customization of the rails_context
177
+
178
+ You can customize the values passed in the `railsContext` in your `config/initializers/react_on_rails.rb`. Here's how.
179
+
180
+ Set the config value for the `rendering_extension`:
181
+
182
+ ```ruby
183
+ config.rendering_extension = RenderingExtension
184
+ ```
185
+
186
+ Implement it like this above in the same file. Create a class method on the module called `custom_context` that takes the `view_context` for a param.
187
+
188
+ See [spec/dummy/config/initializers/react_on_rails.rb](https://github.com/shakacode/react_on_rails/tree/master/spec/dummy/config/initializers/react_on_rails.rb) for a detailed example.
189
+
190
+ ```ruby
191
+ module RenderingExtension
192
+
193
+ # Return a Hash that contains custom values from the view context that will get merged with
194
+ # the standard rails_context values and passed to all calls to render-functions used by the
195
+ # react_component and redux_store view helpers
196
+ def self.custom_context(view_context)
197
+ {
198
+ somethingUseful: view_context.session[:something_useful]
199
+ }
200
+ end
201
+ end
202
+ ```
203
+
204
+ In this case, a prop and value for `somethingUseful` will go into the railsContext passed to all react_component and redux_store calls. You may set any values available in the view rendering context.
205
+
@@ -0,0 +1,73 @@
1
+ # RSpec Configuration
2
+ _Click [here for minitest](./minitest-configuration.md)_
3
+
4
+ # If your webpack configurations correspond to rails/webpacker's default setup
5
+ If you're able to configure your webpack configuration to be run by having your webpack configuration
6
+ returned by the files in `/config/webpack`, then you have 2 options to ensure that your files are
7
+ compiled by webpack before running tests and during production deployment:
8
+
9
+ 1. **Use rails/webpacker's compile option**: Configure your `config/webpacker.yml` so that `compile: true` is for `test` and `production`
10
+ environments. Ensure that your `source_path` is correct, or else `rails/webpacker` won't correctly
11
+ detect changes.
12
+ 2. **Use the react_on_rails settings and helpers**. Use the settings in `config/initializers/react_on_rails.rb`. Refer to [docs/configuration](./configuration.md).
13
+
14
+ ```yml
15
+ config.build_test_command = "NODE_ENV=test RAILS_ENV=test bin/webpack"
16
+ ```
17
+
18
+ Which should you use? If you're already using the `rails/webpacker` way to configure webpack, then
19
+ you can keep things simple and use the `rails/webpacker` options.
20
+
21
+ # Checking for stale assets using React on Rails
22
+
23
+ Because you will probably want to run RSpec tests that rely on compiled webpack assets (typically, your integration/feature specs where `js: true`), you will want to ensure you don't accidentally run tests on missing or stale webpack assets. If you did use stale Webpack assets, you will get invalid test results as your tests do not use the very latest JavaScript code.
24
+
25
+ As mentioned above, you can configure `compile: true` in `config/webpacker.yml` _if_ you've got configuration for
26
+ your webpack in the standard `rails/webpacker` spot of `config/webpack/<NODE_ENV>.js`
27
+
28
+ ReactOnRails also provides a helper method called `ReactOnRails::TestHelper.configure_rspec_to_compile_assets`. Call this method from inside of the `RSpec.configure` block in your `spec/rails_helper.rb` file, passing the config as an argument. See file [lib/react_on_rails/test_helper.rb](../../lib/react_on_rails/test_helper.rb) for more details. You can customize this to your particular needs by replacing any of the default components used by `ReactOnRails::TestHelper.configure_rspec_to_compile_assets`.
29
+
30
+ ```ruby
31
+ RSpec.configure do |config|
32
+ ReactOnRails::TestHelper.configure_rspec_to_compile_assets(config)
33
+ ```
34
+
35
+ You can pass one or more RSpec metatags as an optional second parameter to this helper method if you want this helper to run on examples other than where `:js`, `:server_rendering`, or `:controller` (those are the defaults). The helper will compile webpack files at most once per test run. The helper will not compile the webpack files unless they are out of date (stale). The helper is configurable in terms of what command is used to prepare the files. If you don't specify these metatags for your relevant JavaScript tests, then you'll need to do the following.
36
+
37
+ If you are using Webpack to build CSS assets, you should do something like this to ensure that you assets are built for any specs under `specs/requests` or `specs/features`:
38
+
39
+ ```ruby
40
+ ReactOnRails::TestHelper.configure_rspec_to_compile_assets(config, :requires_webpack_assets)
41
+ config.define_derived_metadata(file_path: %r{spec/(features|requests)}) do |metadata|
42
+ metadata[:requires_webpack_assets] = true
43
+ end
44
+ ```
45
+
46
+ Please take note of the following:
47
+ - If you are using Webpacker, be **SURE** to configure the `source_path` in your `config/webpacker.yml` unless you are using the defaults for webpacker.
48
+
49
+ - This utility uses your `build_test_command` to build the static generated files. This command **must not** include the `--watch` option. If you have different server and client bundle files, this command **must** create all the bundles. If you are using webpacker, the default value will come from the `config/webpacker.yml` value for the `public_output_path` and the `source_path`
50
+
51
+ - If you add an older file to your source files, that is already older than the produced output files, no new recompilation is done. The solution to this issue is to clear out your directory of webpack generated files when adding new source files that may have older dates.
52
+
53
+ - By default, the webpack processes look in the webpack generated files folder, configured via the `config/webpacker.yml` config values of `public_root_path` and `public_output_path`. If the webpack generated files folder is missing, is empty, or contains files in the `config.webpack_generated_files` list with `mtime`s older than any of the files in your `client` folder, the helper will recompile your assets.
54
+
55
+ The following `config/react_on_rails.rb` settings **must** match your setup:
56
+ ```ruby
57
+ # Define the files we need to check for webpack compilation when running tests.
58
+ config.webpack_generated_files = %w( manifest.json )
59
+
60
+ # OR if you're not hashing the server-bundle.js, then you should include your server-bundle.js in the list.
61
+ # config.webpack_generated_files = %w( server-bundle.js manifest.json )
62
+
63
+ # If you are using the ReactOnRails::TestHelper.configure_rspec_to_compile_assets(config)
64
+ # with rspec then this controls what yarn command is run
65
+ # to automatically refresh your webpack assets on every test run.
66
+ config.build_test_command = "yarn run build:test"
67
+ ```
68
+
69
+ If you want to speed up the re-compiling process so you don't wait to run your tests to build the files, you can run your test compilation with the "watch" flags. For example, `yarn run build:test --watch`
70
+
71
+ ![2016-01-27_02-36-43](https://cloud.githubusercontent.com/assets/1118459/12611951/7c56d070-c4a4-11e5-8a80-9615f99960d9.png)
72
+
73
+ ![2016-01-27_03-18-05](https://cloud.githubusercontent.com/assets/1118459/12611975/a8011654-c4a4-11e5-84f9-1baca4835b4b.png)