Recommended Project structure
The React on Rails generator uses the standard Shakapacker convention of this structure:
app/javascript:
├── bundles:
│ # Logical groups of files that can be used for code splitting
│ └── hello-world-bundle.js
├── packs:
│ # only webpack entry files here
│ └── hello-world-bundle.js
Per the example repo shakacode/react_on_rails_demo_ssr_hmr, you should consider keeping your codebase mostly consistent with the defaults for Shakapacker.
Steps to convert from the generator defaults to use a /client
directory for source code
- Move the directory:
mv app/javascript client
- Edit your
/config/shakapacker.yml
file. Change thedefault/source_path
:
source_path: client
Moving node_modules from /
to /client
with a custom webpack setup.
Shakapacker 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.
- Move the
/package.json
to/client/package.json
- Create a
/package.json
that delegates to/client/package.json
."scripts": { "heroku-postbuild": "cd ./client && yarn" },
- If your
node_modules
directory is not at the top level of the Rails project, then you will need to set the ENV value ofSHAKAPACKER_CONFIG
to the location of theconfig/shakapacker.yml
file per rails/webpacker PR 2561. (Notice the change of spelling from Webpacker to Shakapacker)
CSS, Sass, Fonts, and Images
Should you move your styling assets to Webpack? Or stick with the plain Rails asset pipeline. It depends!
Here's a good discussion of this option: Why does Rails 6 include both Webpacker and Sprockets?.
You have 2 basic choices:
Simple Rails Way
This isn't really any technique, as you keep handling all your styling assets using Rails standard tools, such as using the sass-rails gem. Basically, Webpack doesn't get involved with styling. Your Rails layouts just doing the styling the standard Rails way.
Advantages to the Simple Rails Way
- Much simpler! There's no changes really from your current processes.
Using Webpack to Manage Styling Assets
This technique involves customization of the webpack config files to generate CSS, image, and font assets.
Directory structure
/client/app/assets
: Assets for CSS for client app./client/app/assets/fonts
and/client/app/assets/styles
: Globally shared assets for styling. Note, most Sass and image assets will be stored next to the JavaScript files.
Advantages to having Webpack Manage Styles
- You can use CSS modules, which is super compelling once you seen the benefits.
- You can use CSS in JS.
- 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.