关于cesium的引入和其他引入不同,用npm install cesium 然后再import会报错,作为新手,为了正确引入cesium也踩了不少坑,下面把正确引入方式记录一下,也希望能够帮到大家。 第一步:使用脚手架搭建一个vue项目,这里就不过多赘述了
vue create xxx
第二步:引入cesium 在vue项目中 ctrl + ` 新建终端,输入
npm install cesium -s
第三步:在main.js中输入以下代码将cesium作为全局引入
var Cesium = require('cesium/Cesium');
var widgets= require('cesium/Widgets/widgets.css');
Vue.prototype.Cesium = Cesium
Vue.prototype.widgets = widgets
第四步:在主目录下面找到 vue.config.js并打开(如果没有就新建一个),在里面输入以下代码,直接复制就可以 注意:在代码第2行我们引入了copy-webpack-plugin,如果没有安装的小伙伴可能会出现报错情况,安装方式如下:新建一个终端并输入npm i copy-webpack-plugin -s 即可。
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,
publicPath: "./",
outputDir: "dist",
lintOnSave: false,
configureWebpack: {
output: {
sourcePrefix: " ",
},
amd: {
toUrlUndefined: true,
},
resolve: {
alias: {
"@": path.resolve("src"),
cesium: path.resolve(__dirname, cesiumSource),
},
},
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: path.join(cesiumSource, cesiumWorkers), to: "Workers" },
],
}),
new CopyWebpackPlugin({
patterns: [{ from: path.join(cesiumSource, "Assets"), to: "Assets" }],
}),
new CopyWebpackPlugin({
patterns: [{ from: path.join(cesiumSource, "Widgets"), to: "Widgets" }],
}),
new CopyWebpackPlugin({
patterns: [
{
from: path.join(cesiumSource, "ThirdParty/Workers"),
to: "ThirdParty/Workers",
},
],
}),
new webpack.DefinePlugin({
CESIUM_BASE_URL: JSON.stringify("./"),
}),
],
},
});
第五步:在views文件夹下面新建一个文件CesiumView.vue
<template>
<div id="mycesium"></div>
</template>
<script>
import * as Cesium from "../../node_modules/cesium";
export default {
data() {
return {};
},
created() {},
mounted() {
new Cesium.Viewer("mycesium");
},
methods: {},
};
</script>
我在运行的时候出现报错,提示找不到模块cesium,使用import * as Cesium from "../../node_modules/cesium"; 解决了问题,不知道什么原因。
第六步:配置路由,在router/index.js文件下使用import CesiumView from "../views/CesiumView.vue"; 将文件导入进来
import Vue from 'vue'
import VueRouter from 'vue-router'
import CesiumView from "../views/CesiumView.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
component: CesiumView,
},
];
const router = new VueRouter({
routes
})
export default router
最后编译运行就能看到效果了
npm run serve
效果如下:
|