Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

babeljs

d3.js

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?

like image 895
Andrey Bushman Avatar asked Jan 06 '19 16:01

Andrey Bushman


1 Answers

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

like image 63
Jayavel Avatar answered Oct 15 '22 13:10

Jayavel