Webpacker in Development
Learn about how Webpacker is used in development.
We'll cover the following...
In development, we mostly worry about three things: writing our code, getting our code on to the page, and being able to recompile the code quickly and easily.
Writing code using Webpacker
Somewhat uncharacteristically for Rails, Webpacker does not suggest any structure for your code beyond having the entry point be in app/javascript/packs
. The important feature is that you can import files relative to either app/javascript
(for your own code) or node_modules
(for third party code).
That said, some suggestions are as follows:
-
Keep as little code as possible in your actual entry point. It should mostly just import things.
-
Where possible, having multiple modular small pack files is probably better than having a single one. There’s a webpack optimization that makes this optimal from a download standpoint, as well.
-
If you import a directory rather than a file, the module system will automatically import the
index.js
(orindex.ts
) file in that directory. We’ve already seen this in our boilerplate code: the pack importscontrollers
, andcontrollers/index.js
handles the autoload of controller modules. You can use this to modularize your imports somewhat, and make it easy for common imports to be shared across pack files. -
Your framework of choice may have some community standards for how code is structured. If so, you should follow them.
-
I wouldn’t put anything other than entry point files in the
packs
directory, and I wouldn’t create any subdirectories there either, unless I was trying to namespace multiple packs by putting them in different subdirectory. But I wouldn’t use those subdirectories for regular source code. -
It’s tempting, but I think I’d avoid creating a top level
app/javascript/src
directory on the grounds that anything in theapp/javascript
directory is source of some kind or other. -
I would, though, try to separate out CSS into
app/javascript/stylesheet
, as ridiculous as that directory structure sounds. (You could create anapp/stylesheet
and make it a path for webpack, but I think that would be unnecessarily confusing.)
Using packs
To use a pack in your Rails code, you use the helpers javascript_pack_tag
or stylesheet_pack_tag
...