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.
- If you need to continue exposing your CoffeeScript classes to the global namespace, define them on
window
directly:
-class @User
+class window.User
- Replace Sprocket's
require
statement with Webpacker'simport
statement to load dependencies.
-#= require ./person
+import './person'
-class @user extends Person
+class window.user extends window.Person
- Add required npm dependencies to your
package.json
:
yarn add coffeescript coffee-loader
- Define a CoffeeScript loader (e.g. in
config/webpack/loaders/coffee.js
)
module.exports = {
test: /\.coffee$/,
use: [{
loader: 'coffee-loader'
}]
}
- Add the loader to the Webpacker environment (e.g. in
config/webpack/environment.js
)
environment.loaders.prepend('coffee', require('./loaders/coffee'))
- Add your CoffeeScript files to a pack (e.g. in
packs/app.js
). Note thatimport
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
Posted by Michael Leimstädtner to makandra dev (2020-07-31 13:08)