d3.js - 为什么 Babel 7 对一无所知的浏览器使用 require() 函数?

标签 d3.js babeljs

我尝试在我的模块中使用 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 模块语句的构建系统或打包器:

  • Babelify + Browserify
  • Babel + WebPack

  • 这两个工具会将您的 require 调用转换为在浏览器中工作。
  • 编译为 AMD 格式 (transform-es2015-modules-amd) 并在您的应用程序中包含 Require.js [我正在使用它,因为我现有的应用程序在 grunt 上中继,需要]

  • 希望它有所帮助并创建了一个简单的 webpack , babel setup 如果需要,请检查它。 webpack-babel setup

    关于d3.js - 为什么 Babel 7 对一无所知的浏览器使用 require() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54063557/

    相关文章:

    node.js - 如何在发布之前安装已发布的范围包?

    javascript - 在返回之前使用函数

    error-handling - 带有 webpack 的 Babel polyfill

    javascript - 从 Babel 5 迁移到 6 时出错(ReferenceError : exports is not defined)

    javascript - D3.js:圆形剪切路径不起作用?

    graph - D3.js强制布局: How to isolate node groups?

    javascript - 我如何转换 d3 force 指令图以与 angularjs 一起使用?

    javascript - 从 d3.json() 返回数组

    javascript - 如何在 d3.js 中生成 1000 种独特的颜色

    javascript - JS `import` 未定义,可能是循环导入问题?