Home > Back-end >  How to import JS files with esbuild & jsbundling-rails
How to import JS files with esbuild & jsbundling-rails

Time:04-30

I'm moving a Rails 6 app from webpack & webpacker to esbuild & jsbundling-rails

I can't find any documentation on the correct way to import custom js files in application.js, if not using stimulus. Thanks.

CodePudding user response:

Verifying Set Up

Once the jsbundling-rails gem is added to the Gemfile gem "jsbundling-rails" and installed (see the documentation on the repo for installation), you may need to start the javascript watcher with the command yarn build --watch.

Adding Custom JavaScript

You can add custom JavaScript to the /app/javascript directory and then link it on the application.js. Once the custom javascript is added, the bundler should compile the new fingerprinted javascript file in the /app/assets/build directory.

Example

Adding new.js to the /app/javascript

//new.js

alert('hit')

Linking new.js on the application.js

//application.js
// Entry point for the build script in your package.json
import "@hotwired/turbo-rails"
// import "./controllers"
import * as bootstrap from "bootstrap"
import './new.js'

In the terminal which started the watcher, after the new javascript is saved it outputs

[watch] build started (change: "app/javascript/application.js")
[watch] build finished

And there is now the following files in /app/assets/build

//new.js
(() => {
  // app/javascript/new.js
  alert("hit");
})();
//# sourceMappingURL=new.js.map

//new.js.map
{
  "version": 3,
  "sources": ["../../javascript/new.js"],
  "sourcesContent": ["alert('hit')"],
  "mappings": ";;AAAA,QAAM;",
  "names": []
}
  • Related