After digging for a few hours, I don't think this particular issue is a duplicate.
I'm including d3 in a project using Webpack. I'm following the recommended technique of "import * as d3 from 'd3'", but for some reason I'm getting "Uncaught ReferenceError: d3 is not defined". When I look through the outputted bundle file, I see that it imported all the d3 modules, however for some reason the main d3.js file isn't in there. Any clue what's going on?
This is being run in Chrome. When I type "d3" or "window.d3" into the console, it returns "Uncaught ReferenceError: d3 is not defined".
package.json
"dependencies": {
"d3": "^7.1.1",
"fisforformat": "^2.0.0",
"jquery": "^3.6.0"
},
the import call
import * as d3 from 'd3';
webpack.config.js (v5.59.1)
const path = require('path');
module.exports = {
entry: './src/lib.js',
output: {
filename: 'lib.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "swc-loader"
}
}
],
},
};
CodePudding user response:
I figured it out. Webpack encapsulates imported resources and only exposes them to to other modules loaded via Webpack. I had logic in my that was checking if window.d3 existed before attempting to draw a graph and since d3 wasn't getting globally exposed, that check failed. Further, when I was troubleshooting using the console, I wasn't able to see d3 for the same reason. I changed to logic in my code to check for just d3 instead of window.d3 and it started working.
FYI, if you actually need to make something imported global, you can do something like this in you entry js file:
import * as d3 from 'd3';
window.d3 = d3;
Edit: Even better, you can use expose-loader.