我的博客

搭建d3.js开发环境

目录

1、安装node.js 2、初始化项目

创建目录,进入目录,执行命令 npm init -y

然后建立src目录用于存放源码,dist用于存放编译好的代码

3、安装和配置webpack

执行npm install webpack webpack-cli --save-dev

创建文件 webpack.config.js ,写入以下内容

const path = require(‘path’);

module.exports = {
entry: ‘./src/index.js’,
output: {
filename: ‘main.js’,
path: path.resolve(__dirname, ‘dist’)
}
};

修改package.json,在scripts中加入"build": "webpack" 4、安装d3.js

执行 npm install d3 --save

5、编写代码

创建dist/index.html,并写入以下内容

<!doctype html>


Getting Started




创建src/index.js,并写入以下内容

import * as d3 from “d3”;

function SimpleWidget(spec) {
var instance = {}; // <– A
var headline, description; // <– B
instance.render = function () {
var div = d3.select(‘body’).append(“div”);
div.append(“h3”).text(headline); // <– C
div.attr(“class”, “box”)
.attr(“style”, “color:” + spec.color) // <– D
.append(“p”)
.text(description); // <– E
return instance; // <– F
};
instance.headline = function (h) {
if (!arguments.length) return headline; // <– G
headline = h;
return instance; // <– H
};
instance.description = function (d) {
if (!arguments.length) return description;
description = d;
return instance;
};
return instance; // <– I
}
var widget = SimpleWidget({color: “#6495ed”})
.headline(“Simple Widget”)
.description(“This is a simple widget demonstrating functional javascript.”);
widget.render();

6、编译与运行

执行 npm run-script build该命令生成了dist/main.js

在浏览器中打开dist/index.html即可看到代码运行后的效果

参考资料 1、https://webpack.js.org/guides/getting-started/ 2、D3.js数据可视化实战手册 3、https://github.com/NickQiZhu/d3-cookbook/

评论无需登录,可以匿名,欢迎评论!