Posted 10 days ago. Visible to the public.

How to migrate CoffeeScript files from Sprockets to Webpack(er)

If you migrate a Rails application from Sprockets to Webpack(er), you can either transpile your CoffeeScript files to JavaScript or integrate a CoffeeScript compiler to your new process. This checklist can be used to achieve the latter.

  1. If you need to continue exposing your CoffeeScript classes to the global namespace, define them on window directly:
Copy
-class @User +class window.User
  1. Replace Sprocket's require statement with Webpacker's import statement to load dependencies.
Copy
-#= require ./person +import './person' -class @user extends Person +class window.user extends window.Person
  1. Add required npm dependencies to your package.json:
Copy
yarn add coffeescript coffee-loader
  1. Define a CoffeeScript loader (e.g. in config/webpack/loaders/coffee.js)
Copy
module.exports = { test: /\.coffee$/, use: [{ loader: 'coffee-loader' }] }
  1. Add the loader to the Webpacker environment (e.g. in config/webpack/environment.js)
Copy
environment.loaders.prepend('coffee', require('./loaders/coffee'))
  1. Add your CoffeScript files to a pack (e.g. in packs/app.js). Note that import is required to expose your JS classes globally.
Copy
// filePath is a relative path like "./foo.coffee". // The call to "substring" removes the "./" prefix. let preparePath = function(filePath) { return filePath.substring(2); }; modelFiles = require.context('js/models', true, /\.(js|coffee)$/); for(let filePath of modelFiles.keys()) { import(`js/models/${preparePath(filePath)}`) };

See also

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Michael Leimstädtner
Last edit:
about 9 hours ago
by Emanuel De
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Michael Leimstädtner to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more