效果图:
哎呀,刚做前端就遇到了一个知识盲点,如何在vue2中引入cesium?这几天也是煞费苦心!废话不多说,直接上代码!
1.创建vue2项目
2.安装cesium
npm install cesium@1.95.0 -s
3.安装webpack
npm install copy-webpack-plugin@10.2.4
4.安装webpack所需loader
npm install @open-wc/webpack-import-meta-loader
5.配置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 = "Workers";
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false,
configureWebpack: {
externals: {
'cesium': 'Cesium',
},
output: {
sourcePrefix: " ",
},
amd: {
toUrlUndefined: true,
},
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,
}
})
6.main.js中导入cesium的css
import 'cesium/Widgets/widgets.css';
7App.vue 配置style
html,body,#cesiumContainer {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
9.npm run serve!!