基于Webpack的Cesium+Vue2.x应用(推荐)

本文主要讲解vue2.x与cesium的结合,主要参考cesium官网教程(Cesium and Webpack)和github下的cesium-vue项目。

1、使用vue-cli脚手架新建vue项目(vue init webpack 项目名称),引入cesium模块(cnpm install cesium)

image.png

2、修改webpack下的3个配置文件:webpack.base.conf.js、webpack.dev.conf.js、webpack.prod.conf.js。具体如下:

1、修改webpack.base.conf.js文件

(1)增加代码


image.png
const cesiumSource = '../node_modules/cesium/Source';       

(2)增加代码


image.png
    sourcePrefix: ''

    amd: {                                    //flag
        // Enable webpack-friendly use of require in Cesium
        toUrlUndefined: true
    },

(3)增加代码


image.png
'cesium': path.resolve(__dirname, cesiumSource)

(4)增加代码


image.png
{
            //Strip cesium pragmas 删除编译指示               //flag
            test: /\.js$/,
            enforce: 'pre',
            include: path.resolve(__dirname, cesiumSource),
            use: [{
                loader: 'strip-pragma-loader',
                options: {
                    pragmas: {
                        debug: false
                    }
                }
            }]
        },

(5)增加代码


image.png
unknownContextCritical: false  //屏蔽警告
2、修改webpack.dev.conf.js文件

(1)增加代码


image.png
const cesiumSource = 'node_modules/cesium/Source';      //flag
const cesiumWorkers = '../Build/Cesium/Workers';

(2)增加代码


image.png
'CESIUM_BASE_URL': JSON.stringify('') 

(3)增加代码


image.png
      new CopyWebpackPlugin([ { from: path.join(cesiumSource, cesiumWorkers), to: 'Workers' } ]),     //flag
      new CopyWebpackPlugin([ { from: path.join(cesiumSource, 'Assets'), to: 'Assets' } ]),
      new CopyWebpackPlugin([ { from: path.join(cesiumSource, 'Widgets'), to: 'Widgets' } ]),
3、修改webpack.prod.conf.js文件

(1)增加代码


image.png
const cesiumSource = 'node_modules/cesium/Source';      //flag
const cesiumWorkers = '../Build/Cesium/Workers';

(2)增加代码


image.png
'CESIUM_BASE_URL': JSON.stringify('static')

(3)增加代码


image.png
      new CopyWebpackPlugin([ { from: path.join(cesiumSource, cesiumWorkers), to: 'static/Workers' } ]),//flag
      new CopyWebpackPlugin([ { from: path.join(cesiumSource, 'Assets'), to: 'static/Assets' } ]),
      new CopyWebpackPlugin([ { from: path.join(cesiumSource, 'Widgets'), to: 'static/Widgets' } ]),

3、测试

cesiumViewer.vue代码:

<template>
    <div id="cesiumContainer">
    </div>
</template>

<script>
    import Cesium from 'cesium/Cesium';
    import widgets from 'cesium/Widgets/widgets.css';

    export default {
        name: 'cesiumContainer',
        mounted(){
            var viewer = new Cesium.Viewer('cesiumContainer');
        }
    }
</script>

<style scoped>
</style>

推荐阅读更多精彩内容