Webpacker is the default JavaScript compiler in Rails 6. Don't know what the heck is Webpacker, check this out!

I am working on a book on Webpacker and how to effectively use it with Rails. Want to know more and be updated with the progress? Sign up here!

Background

Rails 5.1: Loving JavaScript, System Tests, Encrypted Secrets, and more

Webpacker 3.0: No separate process needed, less config generated

Make Webpacker the default JavaScript compiler for Rails 6

Rails 6.0.0 beta1: Action Mailbox, Action Text, Multiple DBs, Parallel Testing, Webpacker by default

Examples for legacy code

1) require_context

// app/javascript/packs/app.js
// import all files in a folder
require.context('../utils', true)

2) module-resolver

// Before

import "./coffee-maker"

// .babelrc 

{   
  "plugins": [     
              ["module-resolver", { "root": ["./app/javascript"], 
                                    "alias": {} }
              ]   
             ]
}

// After

import "coffee-maker"

3) Exporting webpack modules to global scope

output: {
  // Makes exports from entry packs available to global scope
  library: ['Packs', '[name]'],
  libraryTarget: 'var'
}

// app/javascript/packs/application.js

export { default as CoffeeMaker } from './coffee_maker'

// app/assets/javascripts/application.js

 Packs.application.CoffeeMaker

4) Exporting libraries to global scope

module: {
  rules: [
   {
      test: require.resolve('jquery'),
      use: [{
        loader: 'expose-loader',
        options: '$',
      }, {
        loader: 'expose-loader',
        options: 'jQuery',
      }],
    },
  ],
},

Good luck embracing modern JavsScript in your Rails app.

I am working on a book on Webpacker and how to effectively use it with Rails. Want to know more and be updated with the progress? Sign up here!