目录
1、在vue2项目中下载cesium
2、安装loader
3、更改vue.config.js中的配置
4、main.js中引入
5、App.vue中设置样式
6、新建map.vue 其中代码如下:
7、在App.vue中使用Map组件
8、效果展示:
1、在vue2项目中下载cesium
npm install cesium
可能会出现下载失败报错,重新执行下载
npm config set registry https://registry.npmmirror.com
npm install cesium
2、安装loader
npm install @open-wc/webpack-import-meta-loader
3、更改vue.config.js中的配置
const {defineConfig} = require('@vue/cli-service')
const CopyWebpackPlugin = require("copy-webpack-plugin");const webpack = require("webpack");
const path = require("path");let cesiumSource = "node_modules/cesium/Source";
let cesiumWorkers = "../Build/Cesium/Workers";
module.exports = defineConfig({transpileDependencies: true,lintOnSave: false,configureWebpack: {externals: {'cesium': 'Cesium',},output: {sourcePrefix: " ", // 让webpack 正确处理多行字符串配置 amd参数},amd: {toUrlUndefined: true, // webpack在cesium中能友好的使用require},resolve: {extensions: ['.js', '.vue', '.json'],alias: {"@": path.resolve("src"),cesium: path.resolve(__dirname, cesiumSource),}},plugins: [new CopyWebpackPlugin({patterns: [{from: path.join(cesiumSource, cesiumWorkers), to: "Workers"},{from: path.join(cesiumSource, "Assets"), to: "Assets"},{from: path.join(cesiumSource, "Widgets"), to: "Widgets"},{from: path.join(cesiumSource, "ThirdParty/Workers"), to: "ThirdParty/Workers"}]}),new webpack.DefinePlugin({CESIUM_BASE_URL: JSON.stringify("./"),}),],module: {unknownContextCritical: false,unknownContextRegExp: /\/cesium\/cesium\/Source\/Core\/buildModuleUrl\.js/,rules: [{test: /\.js$/,use: {loader: '@open-wc/webpack-import-meta-loader',},},]},},devServer: {hot: true,open: true,// 代理proxy: {'/api': {target: 'http://localhost:8888/',changeOrigin: true,ws: true,pathRewrite: {'^/api': ''}}},port: 8080,}
})
4、main.js中引入
import 'cesium/Widgets/widgets.css';
引入后控制台会发生报错,此时需要修改cesium/package.json
找到【exports】,加上最后一行:"./Source/Widgets/widgets.css": "./Source/Widgets/widgets.css"
"exports": {"./package.json": "./package.json","./Source/*": "./Source/*","./Source/*.js": null,"./Build/*": "./Build/*","./Build/*.js": null,".": {"types": "./Source/Cesium.d.ts","require": "./index.cjs","import": "./Source/Cesium.js"},"./Source/Widgets/widgets.css": "./Source/Widgets/widgets.css" },
5、App.vue中设置样式
html,body,#cesiumContainer {width: 100%;height: 100%;margin: 0;padding: 0;overflow: hidden;
}
6、新建map.vue 其中代码如下:
<template><div id="cesiumContainer"></div></template><script>import * as Cesium from 'cesium/Cesium'export default {name: 'map',mounted(){this.initCesium()},methods:{initCesium:function (){let viewer = new Cesium.Viewer('cesiumContainer')}}}</script><style scoped></style>
7、在App.vue中使用Map组件
<template><div id="app"><Map></Map></div>
</template>
<script>
import Map from '@/components/map.vue'export default {data(){return {}},components:{Map}}
</script>
<style>
html,body,#cesiumContainer {width: 100%;height: 100%;margin: 0;padding: 0;overflow: hidden;
}
</style>