建项准备
> create-react-app cesium-react
> cd cesium-react
// 解锁出react中的webpack配置文件
> cnpm run eject
解锁配置后,文件结构如下:
|-- .gitignore
|-- package.json
|-- yarn.lock
|-- config
| |-- env.js
| |-- paths.js
| |-- webpack.config.dev.js
| |-- webpack.config.prod.js
| |-- webpackDevServer.config.js
| |-- jest
| |-- cssTransform.js
| |-- fileTransform.js
|-- public
|-- scripts
| |-- build.js
| |-- start.js
| |-- test.js
|-- src
添加cesium到webpack
添加cesium依赖,再对webpack进行配置
cesium依赖安装
copy-webpack-plugin依赖安装(用于资源复制)
> yarn add cesium
> yarn add copy-webpack-plugin
配置webpack:dev与生产环境的配置文件都需要相应修改
引入相关插件,并申明需要用到的配置路径
// Copy Cesium Assets, Widgets, and Workers to a static directory
const CopywebpackPlugin = require("copy-webpack-plugin");
// The path to the Cesium source code
const cesiumSource = '../node_modules/cesium/Source';
const cesiumWorkers = '../Build/Cesium/Workers';
接下来执行官网的:解决webpack编译Cesium的怪癖:
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
// Needed to compile multiline strings in Cesium
sourcePrefix: ''
},
amd: {
// Enable webpack-friendly use of require in Cesium
toUrlUndefined: true
},
node: {
// Resolve node module use of fs
fs: 'empty'
},
这里做一个别名配置,让我们更轻松的使用cesium模块,可以查看webpack文档,学习使用:
resolve: {
alias: {
// Cesium module name
cesium: path.resolve(__dirname, cesiumSource)
}
}
接下来复制资源文件到磁盘目录中,这样页面编译后才能加载到相关资源,比如图片等
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
// Copy Cesium Assets, Widgets, and Workers to a static directory
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' } ]),
// 定义一个环境变量,指定加载静态文件的基础URL地址
new webpack.DefinePlugin({
// Define relative base path in cesium for loading assets
CESIUM_BASE_URL: JSON.stringify('')
})
],
config END
项目中使用Cesium
在src/index.js中引入
import 'cesium/Widgets/widgets.css'
组件中引入cesium使用
import Cesium from "cesium/Cesium";
import React from 'react'
export default class CesiumComponent extends React.Component{
componentDidMount() {
const viewer = new Cesium.Viewer("cesiumContainer");
}
render() {
return <div id="cesiumContainer" />;
}
}
THE END