currently learning Javascript and building a simple web application. Here, I am trying to display a chart using apex charts. When I do not include the import statement highlighted, then the chart displays fine on the webpage, when an import (or any other code within that file) is included, the chart no longer appears on the webpage. I am only starting to understand the asynchronous nature of JS so I have assumed it has got to do something with that. Any help is appreciated!
import { datapoints } from "./main.js"; // When this line is commented out or removed, the chart renders fine
var options = {
chart: {
type: 'candlestick'
},
series: [{
data: [
[1147651200000,67.37,68.38,67.12,67.79],
[1147737600000,68.10,68.25,64.75,64.98],
[1147824000000,64.70,65.70,64.07,65.26],
[1147910400000,65.68,66.26,63.12,63.18],
[1147996800000,63.26,64.88,62.82,64.51],
[1148256000000,63.87,63.99,62.77,63.38],
[1148342400000,64.86,65.19,63.00,63.15],
[1148428800000,62.99,63.65,61.56,63.34],
[1148515200000,64.26,64.45,63.29,64.33],
[1148601600000,64.31,64.56,63.14,63.55],
[1148947200000,63.29,63.30,61.22,61.22],
[1149033600000,61.76,61.79,58.69,59.77]
]
}]
}
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
Browsers support the import statement, but only when enabled in a module script. You can enable a module script by adding type="module" to your HTML script tag. Here's a simple example of setting up import statements for the browser:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<!-- ... -->
<script type="module" src="./script.js" defer></script>
</head>
<body>
<!-- ... -->
</body>
</html>
// script.js
import { datapoints } from "./main.js"; // this should work without errors
// ...
Note that if you do plan to scale an application, you may want to consider using a framework or a bundler such as Webpack, Parcel, or Vite.