为什么 Babel 7 对浏览器使用 require() 函数,而浏览器对此一无所知?

And*_*man 8 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"
  }
}
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:需要未定义

为什么会发生这种情况,我该如何解决问题?

Jay*_*vel 8

是的 require() 没有内置到浏览器中。

Babel 默认将 import 和 export 声明转换为 CommonJS(require/module.exports)。

Babel 不做任何事情,它基本上像const babel = code => code; 通过解析代码,然后再次生成相同的代码。

如果你想在浏览器中运行现代 JavaScript,光靠 Babel 是不够的,你还需要一个支持 CommonJS modules 语句的构建系统或打包器:

  1. Babelify + 浏览器化

  2. Babel + WebPack

这两个工具将转换您的 require 调用以在浏览器中工作。

  1. 编译为 AMD 格式 (transform-es2015-modules-amd) 并在您的应用程序中包含 Require.js [我正在使用它,因为我现有的应用程序在 grunt 上中继,需要]

希望它有所帮助并创建了一个简单的 webpack ,如果需要,可以查看 babel 设置。webpack-babel 设置