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:
-class @User
+class window.User
  1. Replace Sprocket's require statement with Webpacker's import statement to load dependencies.
-#= require ./person
+import './person'

-class @user extends Person
+class window.user extends window.Person
  1. Add required npm dependencies to your package.json:
yarn add coffeescript coffee-loader
  1. Define a CoffeeScript loader (e.g. in config/webpack/loaders/coffee.js)
module.exports = {
  test: /\.coffee$/,
  use: [{
    loader: 'coffee-loader'
  }]
}
  1. Add the loader to the Webpacker environment (e.g. in config/webpack/environment.js)
environment.loaders.prepend('coffee', require('./loaders/coffee'))
  1. Add your CoffeeScript files to a pack (e.g. in packs/app.js). Note that import is required to expose your JS classes globally.
// 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

Michael Leimstädtner Over 3 years ago