I'm fairly new to working with JavaScript-heavy projects like this, so I'm sure there are a lot of things I'm not doing right.
I have a Node project whose file structure looks roughly like
project
|- index.js
|- hello.html
|- package.json
|- public
|- views
|- chart.js
I run the site on my local server with node index.js
. I have express installed, and in index.js
I'm using it to route the request '/'
to the file hello.html
. Inside my html file I'm importing a js script from chart.js
like
<head>
<script type="text/javascript" src="/views/chart.js"></script>
</head>
If I write code in chart.js
(like console logging) then it works as expected, so I know my files are connected like I want. My problem is that I have a Node module installed (D3) that I'm trying to use in chart.js
to make a bar chart, but I haven't gotten it to work. If I put const d3 = require('d3')
in my index.js
file and try to use d3
in chart.js
file I get an Uncaught ReferenceError because d3
is not found; on the other hand if I put const d3 = require('d3')
directly in chart.js
then require
is not found (based on some searches I learned this is because require
is a Node thing and not a Browser thing).
Can someone please tell me a simple way of using an external library (like D3) in an imported javascript file? Do I need to figure out RequireJS (which is the official answer to this related question but seems overly complicated to my beginner eyes) or can I re-structure my project/use a different approach to make it work somehow?