上一节学习了在一个简单的html文件中使用cesium,但是在当前前端开发的领域,这已经是一种非常原始的开发方式,一般在实际工作中我们都会使用一些脚手架工具来搭建项目,webpack就是一个非常常用的一个工具,像vueCLI、create-react-app等常用的脚手架都是机遇webpack开发的,今天就来学习,webpack下如何来使用cesium。
- 新建项目。命令行中执行以下代码
npm init -y
npm i webpack webpack-cli copy-webpack-plugin html-webpack-plugin webpack-dev-server style-loader url-loader css-loader -D
npm i cesium -S
- 在
package.json中添加如下代码
"scripts": {
"build": "webpack --config webpack.config.js",
"start": "webpack serve --config webpack.config.js --open"
}
- 新建
index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
#azu-cesium-study {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<div id="azu-cesium-study"></div>
</body>
</html>
- 新建
src/main.js文件
import { Viewer } from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";
new Viewer("azu-cesium-study");
这时去访问 index.html是看不到任何效果的,我们还需要去配置webpack来实现一个工程化的项目。
- 新建
webpack.config.js文件
// The path to the CesiumJS source code
const cesiumSource = 'node_modules/cesium/Source';
const cesiumWorkers = '../Build/Cesium/Workers';
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: __dirname,
entry: {
app: './src/main.js'
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
sourcePrefix: ''
},
resolve: {
fallback: { "https": false, "zlib": false, "http": false, "url": false },
mainFiles: ['index', 'Cesium']
},
module: {
rules: [{
test: /.css$/,
use: [ 'style-loader', 'css-loader' ]
}, {
test: /.(png|gif|jpg|jpeg|svg|xml|json)$/,
use: [ 'url-loader' ]
}]
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html'
}),
// Copy Cesium Assets, Widgets, and Workers to a static directory
new CopyWebpackPlugin({
patterns: [
{ from: path.join(cesiumSource, cesiumWorkers), to: 'Workers' },
{ from: path.join(cesiumSource, 'Assets'), to: 'Assets' },
{ from: path.join(cesiumSource, 'Widgets'), to: 'Widgets' }
]
}),
new webpack.DefinePlugin({
// Define relative base path in cesium for loading assets
CESIUM_BASE_URL: JSON.stringify('')
})
],
mode: 'development',
devtool: 'eval',
};
此时执行 npm start就会自动打开浏览器,并访问 localhost:8080 就可以看到成功展示地球了,同样的执行npm run build就会自动生成打包好的静态文件。