Read more

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

Michael Leimstädtner
July 31, 2020Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot
Michael Leimstädtner
July 31, 2020Software engineer at makandra GmbH
Posted by Michael Leimstädtner to makandra dev (2020-07-31 15:08)