0. 前言

本文档使用的vue cli工具版本为4.5.9

image.png

1. 创建vue基本项目

1.1 安装vue cli

  1. npm install -g @vue/cli
  2. # OR
  3. yarn global add @vue/cli

1.2 创建vue项目(以default配置为例)

  1. vue create cesium-demo

项目创建完成后,得到的目录结构如下:
image.png
手动添加vue.config.js

2. 安装和配置cesium

2.1 安装cesium依赖

  1. npm install cesium
  2. # OR
  3. yarn add cesium

2.2 安装配置所需工具copy-webpack-plugin

  1. npm install copy-webpack-plugin -D
  2. # OR
  3. yarn add copy-webpack-plugin -D

3. 配置vue.config.js

配置文件如下,vue.config.js中,configureWebpack内的内容为一个对象时,内容会被webpack-merge合并到最终配置中,所以将cesium的文件配置挪一部分过来即可

  1. // The path to the CesiumJS source code
  2. const cesiumSource = 'node_modules/cesium/Source';
  3. const cesiumWorkers = '../Build/Cesium/Workers';
  4. const path = require('path');
  5. const webpack = require("webpack");
  6. const CopyPlugin = require("copy-webpack-plugin");
  7. module.exports = {
  8. configureWebpack: {
  9. output: {
  10. sourcePrefix: ' ',
  11. },
  12. amd: {
  13. toUrlUndefined: true,
  14. },
  15. plugins: [
  16. // Copy Cesium Assets, Widgets, and Workers to a static directory
  17. new CopyPlugin({ patterns: [{ from: path.join(cesiumSource, cesiumWorkers), to: 'Workers' }] }),
  18. new CopyPlugin({ patterns: [{ from: path.join(cesiumSource, 'Assets'), to: 'Assets' }] }),
  19. new CopyPlugin({ patterns: [{ from: path.join(cesiumSource, 'Widgets'), to: 'Widgets' }] }),
  20. new webpack.DefinePlugin({
  21. // Define relative base path in cesium for loading assets
  22. CESIUM_BASE_URL: JSON.stringify("")
  23. }),
  24. ],
  25. module: {
  26. // Removes these errors: "Critical dependency: require function is used in a way in which dependencies cannot be statically extracted"
  27. // https://github.com/AnalyticalGraphicsInc/cesium-webpack-example/issues/6
  28. unknownContextCritical: false,
  29. unknownContextRegExp: /\/cesium\/cesium\/Source\/Core\/buildModuleUrl\.js/
  30. }
  31. }
  32. };

4. 创建cesium实例

  1. // App.vue
  2. <template>
  3. <div id="cesiumContainer"></div>
  4. </template>
  5. <script>
  6. import "cesium/Build/Cesium/Widgets/widgets.css";
  7. import * as Cesium from "cesium";
  8. export default {
  9. name: 'App',
  10. mounted() {
  11. new Cesium.Viewer("cesiumContainer");
  12. }
  13. }
  14. </script>

效果展示如下:
image.png

5. 注意事项

copy-webpack-plugin的版本不能是现在最新的7.0.0(该版本支持webpack5),如果使用该版本的插件,会出现编译错误。

image.png