我尝试在我的模块中使用 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"
}
}
Run Code Online (Sandbox Code Playgroud)
请注意targets
我指出我感兴趣的 Web 浏览器版本的部分。浏览器对require
函数一无所知。只有 Node.js 知道它。
这是我的源代码:
import * as d3 from 'd3';
function draw(data) {
// ...
}
d3.json('../data/some-data.json', draw);
Run Code Online (Sandbox Code Playgroud)
但是我看到 Babel 7 代码生成结果包含require
函数:
"use strict";var d3=_interopRequireWildcard(require("d3"));...
因此我在浏览器中收到运行时错误:
未捕获的 ReferenceError:需要未定义
为什么会发生这种情况,我该如何解决问题?
是的 require() 没有内置到浏览器中。
Babel 默认将 import 和 export 声明转换为 CommonJS(require/module.exports)。
Babel 不做任何事情,它基本上像const babel = code => code
; 通过解析代码,然后再次生成相同的代码。
如果你想在浏览器中运行现代 JavaScript,光靠 Babel 是不够的,你还需要一个支持 CommonJS modules 语句的构建系统或打包器:
Babelify + 浏览器化
Babel + WebPack
这两个工具将转换您的 require 调用以在浏览器中工作。
希望它有所帮助并创建了一个简单的 webpack ,如果需要,可以查看 babel 设置。webpack-babel 设置
归档时间: |
|
查看次数: |
3002 次 |
最近记录: |