Webpacker in Development

Learn about how Webpacker is used in development.

In development, we mostly worry about three things: writing our code, getting our code onto 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 our code beyond having the entry point be in app/packs/entrypoints. The important feature is that we can import files relative to either app/packs (for our own code) or node_modules (for third-party code).

That said, here are some suggestions:

  • Keep as little code as possible in your actual entry point, it should mostly be imports.

  • 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.

  • If you import a directory, rather than a file, the module system will automatically import the index.js (or index.ts) file in that directory. We’ve already seen this in our boilerplate code: the pack imports controllers and controllers/index.js handles the autoload of controller modules. You can use this to modularize your imports somewhat and make it easy to share common imports across pack files.

  • Your framework of choice may have some community standards for how code is structured. If so, you should follow them.

  • You should not put anything other than entry point files in the entrypoints directory, and you should not create any subdirectories there either, since you will not be using those subdirectories for regular source code.

  • Avoid creating a top-level app/packs/src directory on the ground that anything in the app/packs directory is a source of some kind or other. Try to be more specific about top level names. You can, though, separate ...