Search code examples
ruby-on-railsd3.jswebpacker

ReferenceError: Can't find variable: d3 in new rails6 application with webpacker


I am working on a personal project with rails 6 and d3js. In fact trying to prepare configuration to start :-)

I used yarn add [email protected] -T to install d3js and appended line

import * as d3 from "d3";

to my javascript/packs/application.js

My problem is I am not able to access d3 in the console. Webpacker is not in my comfort zone yet!


Solution

  • Webpack does not export anything to the global scope by default. Anything you import within your Webpack bundles is within the local scope of the module represented by the file you’re working in.

    To make a variable available to the global scope, you have to expose it somehow. You could configure something like expose-loader to do this. You can instead assign the variable to the global scope, i.e., window, after importing it:

    // app/javascript/packs/application.js
    import * as d3 from "d3"
    window.d3 = d3