简体   繁体   English

使用 browserify 捆绑 D3 库的问题

[英]Issue with using browserify to bundle D3 library

I've been struggling with bundling D3 library using browserify.我一直在努力使用 browserify 捆绑 D3 库。 I've done these steps:我已经完成了这些步骤:

  1. Used require function in a module file and give it as an argument the library name ("d3")在模块文件中使用 require function 并将其作为参数提供库名称(“d3”)
  2. Referenced the module file and bundle.js file in a html document在 html 文档中引用了模块文件和 bundle.js 文件
  3. In a directory containing the module file ran command: browserify module.js > bundle.js在包含模块文件的目录中运行命令:browserify module.js > bundle.js

After I ran the command I got this:在我运行命令后,我得到了这个:

....\node_modules\d3\src\index.js:1 export * from "d3-array"; ....\node_modules\d3\src\index.js:1 export * from "d3-array"; ^ ParseError: 'import' and 'export' may appear only with 'sourceType: module' ^ ParseError: 'import' 和 'export' 可能只与 'sourceType: module' 一起出现

I'm completely clueless what I'm doing wrong.我完全不知道我做错了什么。

Before I give you a solution I want to give you the context to the actual problem.在我给你一个解决方案之前,我想给你一个实际问题的背景。

Browserify allows you to combine multiple javascript files into one file. Browserify 允许您将多个 javascript 文件合并到一个文件中。 This really just saves you from needing to include multiple <script> tags in your html.这确实使您无需在 html 中包含多个<script>标签。

From my perspective it is a cleaner, simpler version of webpack/rollup but, less versatile.从我的角度来看,它是 webpack/rollup 的一个更干净、更简单的版本,但通用性较差。

D3 appears to be written in a version of javascript that supports import/export statements and uses Rollup to convert it to vanilla javascript that the browser (and browserify) can understand. D3 似乎是用 javascript 版本编写的,该版本支持导入/导出语句并使用 Rollup 将其转换为浏览器(和 browserify)可以理解的普通 javascript。

The Answer答案

Import the final version of d3 that is transpiled already.导入已经转译的 d3 最终版本。

const d3 = require('d3/dist/d3');


// do something with d3 here
const targetElem = d3.select('#target');

targetElem.text('HELLO WORLD');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM