Why Babel 7 uses require() function for browser which knows nothing about it?

醉酒当歌 提交于 2020-07-03 03:04:19

问题


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?


回答1:


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:

  1. Babelify + Browserify

  2. Babel + WebPack

These two tools will transform your require calls to work within the browser.

  1. Compile to AMD format (transform-es2015-modules-amd) and include Require.js in your application [I am using this since my existing app relays on grunt, require]

Hope it helps and created a simple webpack , babel setup check it out if you need. webpack-babel setup



来源:https://stackoverflow.com/questions/54063557/why-babel-7-uses-require-function-for-browser-which-knows-nothing-about-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!