代码之家  ›  专栏  ›  技术社区  ›  Andrey Bushman

为什么Babel7对不了解它的浏览器使用require()函数?

  •  2
  • Andrey Bushman  · 技术社区  · 7 年前

    我尝试在我的模块中使用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 我指出,我对Web浏览器的版本感兴趣。浏览器不知道 require 功能。只有node.js知道。

    这是我的源代码:

    import * as d3 from 'd3';
    
    function draw(data) {
        // ...
    }
    
    d3.json('../data/some-data.json', draw);
    

    但我看到babel 7代码生成结果包含 要求 功能:

    "use strict";var d3=_interopRequireWildcard(require("d3"));...

    因此,我在浏览器中得到运行时错误:

    未捕获的引用错误:未定义Require

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   Jayavel    7 年前

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

    babel默认将导入和导出声明转换为commonjs(require/module.exports)。

    巴别塔什么都不做,基本上表现得像 const babel = code => code ; 通过解析代码,然后再次生成相同的代码。

    如果您想在浏览器中运行现代javascript,babel本身就不够了,您还需要一个支持commonjs模块语句的构建系统或bundler:

    1. Babelify+浏览

    2. 巴贝尔+ WebPACK

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

    1. 编译为AMD格式(transform-es2015-modules-amd),并在应用程序中包含require.js [我正在使用这个,因为我现有的应用程序在呼噜声中中继,需要]

    希望它有帮助,并创建了一个简单的Webpack,babel安装程序,如果您需要的话,请检查一下。 webpack-babel setup

    推荐文章