I try to use d3.js in my module. I use Babel 7 for transpiling my code sources.
This is my package.json
:
{
"name": "d3_learning",
"version": "1.0.0",
"description": "",
"main": "index.js",
"directories": {
"test": "test"
},
"scripts": {
"build": "babel src --out-dir dist --source-maps --minified --no-comments",
"build:watch": "npm run build -- -w"
},
"babel": {
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "entry",
"targets": {
"firefox": "64",
"opera": "57",
"chrome": "71",
"edge": "44",
"ie": "11"
}
}
]
]
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.2.3",
"@babel/core": "^7.2.2",
"@babel/node": "^7.2.2",
"@babel/polyfill": "^7.2.5",
"@babel/preset-env": "^7.2.3",
"@babel/register": "^7.0.0"
},
"dependencies": {
"d3": "^5.7.0"
}
}
Pay attention in the targets
section I pointed the versions of web browsers are interest for me. Browsers know nothing about require
function. Only Node.js knows about it.
This is my source code:
import * as d3 from 'd3';
function draw(data) {
// ...
}
d3.json('../data/some-data.json', draw);
But I see Babel 7 code generation result contains require
function:
"use strict";var d3=_interopRequireWildcard(require("d3"));...
Therefore I get runtime error in the browser:
Uncaught ReferenceError: require is not defined
Why does it happen and how can I solve the problem?
Yes require() is not built into the browser.
Babel converts import and export declaration to CommonJS (require/module.exports) by default.
Babel doesn't do anything,It basically acts like const babel = code => code
;
by parsing the code and then generating the same code back out again.
If you want to run modern JavaScript in the browser, Babel on its own is not enough, you also need a build system or bundler that supports CommonJS modules statements:
Babelify + Browserify
Babel + WebPack
These two tools will transform your require calls to work within the browser.
Hope it helps and created a simple webpack , babel setup check it out if you need. webpack-babel setup
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With