Rails: Enable Coffeescript with Webpacker
We can already write JavaScript in ES6 syntax with Webpacker. But if you're in the transition phase to migrate an old Rails app from Sprockets (Asset Pipeline) to Webpacker, you might still want to keep your Coffeescript files in use.
The default setting of Webpacker doesn't support Coffeescript. There is a handy command to install it.
Install coffee-loader
Rails Webpacker has provided the installation script to easily enable coffeescript:
Run the command under your rails app directory.
rails webpacker:install:coffee
This will generate the configurations, as well as a test file app/javascript/packs/hello_coffee.coffee
for you.
Verify it's working
Include it in the application layout file:
<%= javascript_pack_tag 'hello_coffee' %>
Reload the page, you should be able to see this message from the console:
Hello world from coffeescript
Then remove the test file and revert the change:
rm app/javascript/packs/hello_coffee.coffee
git checkout app/views/layouts/application.html.erb
Behind the scenes
The installation script is convenient. But it's still worth to understand what's happening behind the scenes. Webpacker as one of the Rails family members, has its own convention. Getting familiar with it is gonna help you further configure Webpack.
Here is a complete diff of the changes, equivalent of the installation script.
yarn add coffeescript coffee-loader
const { environment } = require('@rails/webpacker')
const coffee = require('./loaders/coffee')
environment.loaders.append('coffee', coffee)
extensions:
- .coffee
- .js
module.exports = {
test: /\.coffee(\.erb)?$/,
use: [{
loader: 'coffee-loader'
}]
}
Tested in Rails 5.2 with Webpacker 3.4.
References
Clap to support the author, help others find it, and make your opinion count.