用习惯了webpack
后,不论是项目开发,还是做些简单的demo
,都喜欢用webpack
来构建,使用起来会方便很多,这里主要介绍下webpack
与cesium
集成。这里就不详细介绍怎么配置webpack
了,直接上代码吧,代码中有注释,看懂还是没问题的。
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopywebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack')
const cesiumSource = 'node_modules/cesium/Source';
const cesiumWorkers = '../Build/Cesium/Workers';
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
//需要编译Cesium中的多行字符串
sourcePrefix: ''
},
amd: {
//允许Cesium兼容 webpack的require方式
toUrlUndefined: true
},
node: {
// 解决fs模块的问题(Resolve node module use of fs)
fs: 'empty'
},
resolve: {
alias: {
// Cesium模块名称
cesium: path.resolve(__dirname, cesiumSource)
}
},
devServer: {
contentBase: './../dist',
host: 'localhost',
port: 8089
},
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',
}),
// 拷贝Cesium 资源、控价、web worker到静态目录
new CopywebpackPlugin([{ from: path.join(cesiumSource, cesiumWorkers), to: 'Workers' }]),
new CopywebpackPlugin([{ from: path.join(cesiumSource, 'Assets'), to: 'Assets' }]),
new CopywebpackPlugin([{ from: path.join(cesiumSource, 'Widgets'), to: 'Widgets' }]),
new webpack.DefinePlugin({
//Cesium载入静态的资源的相对路径
CESIUM_BASE_URL: JSON.stringify('')
})
]
};
package.json
{
"name": "cesium-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --config webpack.config.js --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cesium": "^1.67.0"
},
"devDependencies": {
"copy-webpack-plugin": "^5.1.1",
"css-loader": "^3.4.2",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^1.1.3",
"url-loader": "^3.0.0",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>cesium-demo</title>
<style>
#cesiumContainer,body,html{
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="cesiumContainer"></div>
</body>
</html>
index.js
const Cesium = require('cesium/Cesium');
require('cesium/Widgets/widgets.css');
class CesiumIndex {
constructor(){
this.init()
}
init(){
this.viewer = new Cesium.Viewer('cesiumContainer');
}
}
const obj = new CesiumIndex();