在 webpack 中使用 ECharts
Webpack 是目前比较流行的模块打包工具,你可以在使用 webpack 的项目中轻松的引入和打包 ECharts。
使用webpack打包ECharts的步骤:
① 使用npm init
命令创建一个package.json文件。
② 使用npm install echarts --save
命令安装ECharts。
③ 创建一个webpack.config.js文件,用于配置webpack。
④ 编写代码。
⑤ 启动项目。
相关阅读:
启动项目时需要webpack-cli(我对webpack不太了解)。我在本地全局安装了webpack相关的包。
// package.json
{
"name": "myproject2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"dev": "webpack-dev-server --open",
"build": "webpack -p"
},
"author": "",
"license": "ISC",
"dependencies": {
"echarts": "^4.6.0"
}
}
// webpack.config.js
module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js'
}
};
// index.js
var echarts = require('echarts');
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 绘制图表
myChart.setOption({
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
});
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="main" style=" 600px;height:400px;"></div>
<script type="text/javascript" src="bundle.js"></script>
</body>
</html>
启动项目后,在浏览器看到如下图表。
参考: