Web前端笔记-使用Webpack调用echarts画图

有如下几个步骤,在此记录下!

1. 安装npm;

2. 安装cnpm;

3. 初始化webpack项目:

npm init -y

3. 下载依赖:

cnpm i -D webpack webpack-cli

4. 下载echarts依赖:

cnpm i -S echarts

5. 这个时候会出现node_modules的文件夹,新建src目录以及src/index.js,新建/index.html及webpack.config.js

这里将package.json中的:

"test": "echo \"Error: no test specified\" && exit 1"

改为:

"build": "webpack"

完整代码如下:

{
  "name": "webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.5.0",
    "webpack-cli": "^4.2.0"
  },
  "dependencies": {
    "echarts": "^4.9.0"
  }
}

6. 将webpack.config.js配置好,打包的文件改如何输出:

const path = require('path')

module.exports = {

    entry: path.resolve(__dirname, './src/index.js'),
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: "index-bundle.js"
    }
}

7. 对应的文件如下:

index.js

import EChars from 'echarts'

const charDom = document.getElementById('chart')
const chart = EChars.init(charDom)
chart.setOption({
    title: {
        text: 'test'
    },
    xAxis: {
        data: ['一个', '两个', '三个', '四个']
    },
    yAxis: {},
    series: {
        type: 'bar',
        data: [100, 200, 300, 400]
    }
})

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <style>
        #chart{
            width: 600px;
            height: 600px;
        }
    </style>

</head>

<body>
<div id="chart"></div>
<script src="dist/index-bundle.js"></script>
</body>

</html>

8. 构建项目:

npm run build

这里要注意

这个生成的目录和文件都是和webpack.config.js相关的

比如这个index-bundle.js

 

程序运行截图如下:

源码打包下载地址:

https://github.com/fengfanchen/frontUI/tree/master/webpackEcharts

 

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页