How to import JS files with esbuild & jsbundling-rails

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.

1 answer

  • answered 2022-04-29 10:46 Joe Thor

    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": []
    }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum