Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

javascript - 为什么在我的React应用程序的Chrome控制台中未定义d3?(Why is d3 undefined in Chrome console in my React app?)

I am importing the d3.js library in my React app like this:

(我正在像这样在我的React应用程序中导入d3.js库:)

import * as d3 from "d3";

I am creating a basic world map, which is also displayed correctly in the browser.

(我正在创建一个基本的世界地图,它也可以在浏览器中正确显示。)

However, when I try to do something like this in Chrome console:

(但是,当我尝试在Chrome控制台中执行以下操作时:)

d3.select("path")

I am getting an error:

(我收到一个错误:)

Uncaught ReferenceError: d3 is not defined

(未捕获的ReferenceError:未定义d3)

I guess it has something to do how React works, and being a novice in React right now I don't know what i am missing here right now.

(我猜它与React的工作方式有关,并且作为React的新手,我现在不知道我现在在这里缺少什么。)

Anybody can help?

(有人可以帮忙吗?)

  ask by JoeBe translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because webpack (or any other bunder) holds it in module scope.

(因为webpack(或任何其他废话)将其保存在模块范围内。)

To prevent collisions between modules, bundlers wrap those with functions.

(为防止模块之间发生冲突,捆绑器将其与功能包装在一起。)

You can consider all imports, as local function variables:

(您可以将所有导入视为本地函数变量:)

function yourModule(require) {
  const d3 = require('d3');

  // you can use d3 here within your module
}

you're not able to use it here, somewhere outside

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...