I'm trying to use d3.js in a Rails 6 app with Webpacker and I'm getting Uncaught ReferenceError: d3 is not defined
.
I added d3 using yarn add d3
.
My package.json
file:
{
"name": "example",
"private": true,
"dependencies": {
...
"d3": "^5.15.0",
...
},
"version": "0.1.0",
"devDependencies": {
"webpack-dev-server": "^3.1.14"
}
}
/app/javascript/packs/application.js
:
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("d3")
...
In another JS file I added the following as a way to ensure it's loading properly:
...
console.log("test");
const div = d3.selectAll("div");
...
I ran rails s
to restart the Rails server, then reloaded the page.
The log statement is appearing in the console but the d3 line is returning Uncaught ReferenceError: d3 is not defined
.
You need to import d3 as a variable to be able to reference it in a Webpack-bundled JS file:
import * as d3 from "d3"
window.addEventListener('DOMContentLoaded', () => {
d3.selectAll("div")
.append("p")
.text("Hello, World!")
})
Here's a demo: https://github.com/rossta/rails6-webpacker-demo/compare/example/d3