我尝试在我的模块中使用 d3.js。我使用 Babel 7 来编译我的代码源。
这是我的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"
}
}
关注
targets
我指出网络浏览器的版本对我很感兴趣。浏览器对 require
一无所知功能。只有 Node.js 知道。这是我的源代码:
import * as d3 from 'd3';
function draw(data) {
// ...
}
d3.json('../data/some-data.json', draw);
但我看到 Babel 7 代码生成结果包含
require
功能:"use strict";var d3=_interopRequireWildcard(require("d3"));...
因此我在浏览器中遇到运行时错误:
Uncaught ReferenceError: require is not defined
为什么会发生,我该如何解决这个问题?
最佳答案
是的 require() 没有内置在浏览器中。
Babel 默认将 import 和 export 声明转换为 CommonJS (require/module.exports)。
Babel 什么都不做,它基本上就像 const babel = code => code
;
通过解析代码,然后再次生成相同的代码。
如果你想在浏览器中运行现代 JavaScript,仅靠 Babel 是不够的,你还需要一个支持 CommonJS 模块语句的构建系统或打包器:
这两个工具会将您的 require 调用转换为在浏览器中工作。
希望它有所帮助并创建了一个简单的 webpack , babel setup 如果需要,请检查它。 webpack-babel setup
关于d3.js - 为什么 Babel 7 对一无所知的浏览器使用 require() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54063557/