【问题标题】:D3 Geo Projection plugin cannot find module 'fs'D3 Geo Projection 插件找不到模块“fs”
【发布时间】:2016-05-05 05:34:19
【问题描述】:

我正在尝试在 React 组件中显示 D3 地理投影。

查看任何页面时,D3 Geo 投影模块内部都会出现此错误:

对象不支持属性或方法“readFileSync”

在模块的 index.js 中的这一行抛出:

module.exports = new Function("d3", 
  fs.readFileSync(path.join(__dirname, "d3.geo.projection.js"), "utf-8"));

以下是作为依赖项添加到package.json 的模块:

"d3": "^3.5.16",
"d3-geo-projection": "^0.2.16",
"topojson": "^1.6.25"

以下是我的GeoMap React 组件使用 D3 地理投影插件的代码:

var React = require('react');
var ReactDOM = require('react-dom');
var d3 = require("d3");

require("d3-geo-projection")(d3);

var d3GeoMap = {};

d3GeoMap.create = function(el, props, state) {
    var svg = d3.select(el).append("svg")
        .attr("class", "geoChart")
        .attr("width", props.width)
        .attr("height", props.height);

    this.update(el, state);
};

d3GeoMap.update = function(el, state) {
    d3.select(el).select("svg").append("rect")
        .data(state.data)
        .enter()
        .attr("class", "map")
        .attr("d", d3.geo.path().projection(d3.geo.mercator()));
};

var GeoMap = React.createClass({
    propTypes: {
        data: React.PropTypes.object
    },

    componentDidMount: function() {
        var el = this.refs.geoRoot;
        d3GeoMap.create(el,
            {
                width: 900,
                height: 900
            },
            {
                data: this.props.data
            });
    },

    render: function() {
        return (<div ref="geoRoot"></div>);
    }
});

module.exports = GeoMap;

注意:当点击任何页面时都会发生此错误,即使是不使用我的GeoMap 组件的页面。

有人知道为什么 D3 Geo Projection 插件找不到“fs”模块吗?

【问题讨论】:

  • 你用的是什么捆绑器?
  • 我正在使用 Webpack 和 Babel。

标签: node.js d3.js reactjs d3.geo


【解决方案1】:

require("d3-geo-projection") 捆绑时假定 fs.readFileSync 被替换为实际代码,例如在 browserify 中使用 brfs transform 完成

但是 index.js 文件只是在执行以下操作

module.exports = function (d3) {
  // all the code of ./d3.geo.projection.js is included here
}

因此,如果您没有使用带有此转换的捆绑器,请改用此

var d3 = require("d3");
// assumes that d3 is already defined here
require("d3-geo-projection/d3.geo.projection")

【讨论】:

  • 谢谢!!这成功了。不过,为了澄清这对我来说是如何工作的,我将建议的代码块放入我的 react 组件中,并从 D3 Geo Projection 的 index.js 文件中删除了 module.exports = new Function("d3", fs.readFileSync(path.join(__dirname, "d3.geo.projection.js"), "utf-8"));
猜你喜欢
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 2017-02-12
  • 2017-09-06
  • 2019-06-11
  • 2021-08-22
  • 2020-06-28
  • 2021-09-06
相关资源
最近更新 更多