Cesium intermediate tutorial 10 - cesium JS and webpack

Keywords: Javascript Front-end Webpack gis cesium

webpack is a popular and powerful tool for packaging JavaScript modules. It allows developers to construct code and assets in an intuitive way, and use simple require statements to load different types of files as needed. When built, it tracks code dependencies and packages these modules into one or more packages loaded by the browser.

In the first half of this tutorial, we built a simple Web application from scratch, used webpack, and then covered the next steps of integration Cesium npm module . If you like to use Cesium JS to develop Web applications, webpack is a good choice. If you are new to Cesium and want to learn how to build your first sample application, please check it out Getting Started Turtorial.

In the second part, we will explore more advanced Webpack configurations to optimize applications that use cesium JS.

In the official cesium-webpack-example The complete code and tips for optimizing the CesiumJS webpack application can be found in.

Prerequisites

  • Basic knowledge of command line, JavaScript, and Web development.
  • An IDE or code editor. The developers of the Cesium team use Visual Studio Code, but there is no problem with a minimal code editor (such as Sublime text).
  • Node.js is installed. We recommend using the latest LTS version.

Create a basic webpack app

In this section, we will describe how to set up a basic Web application using webpack and development server. If you have already set up an application and only want to add cesiumjs, skip Add CesiumJS to a webpack app.

Initialize an app with npm

Create a new cesium webpack for your application. Open the console, navigate to the new directory, and run the following command:

npm init

Follow the prompts and fill in all the details about the application. Press enter to use the default value. This will create package.json.

Create the app code

Create an src directory for our application code. When we build the application, webpack will generate distribution files in the dist directory.

Create src/index.html and add code to the template HTML page.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <title>Hello World!</title>
  </head>
  <body>
    <p>Hello World!</p>
  </body>
</html>

Next, create an entry point for the application. This is the entry point from which the webpack finds all the javascript source code and dependencies of the package.

Create src/index.js and add the following code:

console.log('Hello World!');

Install and configure webpack

To start installing webpack:

npm install --save-dev webpack

Configuration configuration

Create webpack.config.js to define the webpack configuration object.

const path = require('path');

const webpack = require('webpack');

module.exports = {
    context: __dirname,
    entry: {
        app: './src/index.js'
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
    }
};

context specifies the basic path of the file. Entry is used to specify the package. In this case, the entry point of the app package is src/index.js. webpack will output the packaged app.js to the dist folder.

Loaders load

Webpack loads everything like a module. Use loaders to load CSS and other asset files. Install style loader, CSS loader, and URL loader.

npm install --save-dev style-loader css-loader url-loader

Add two modules.rules in webpack.config.js: one for css files and the other for other static files. For each, test defines the type of file to load, and use specifies the list of loaders.

const path = require('path');

const webpack = require('webpack');

module.exports = {
    context: __dirname,
    entry: {
        app: './src/index.js'
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [{
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
        }, {
            test: /\.(png|gif|jpg|jpeg|svg|xml|json)$/,
            use: [ 'url-loader' ]
        }]
    }
};

Plugins plug-in

Define index.html and use a webpack called HTML webpack plugin   The plugin injects the package into the page.

npm install --save-dev html-webpack-plugin

Reference the plug-in in webpack.config.js and inject it into plugins. Pass in src/index.html as our template.

const path = require('path');

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    context: __dirname,
    entry: {
        app: './src/index.js'
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [{
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
        }, {
            test: /\.(png|gif|jpg|jpeg|svg|xml|json)$/,
            use: [ 'url-loader' ]
        }]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        })
    ]
};

The configuration file is a javascript file, so we can introduce other node modules and perform operations.

Bundle the app

Use package.json to define scripts that can be called using npm. Add the build command.

  "scripts": {
    "build": "node_modules/.bin/webpack --config webpack.config.js"
  }

This script calls Webpack and passes it into the webpack.config.js configuration file.

We use a local installation of webpack and webpack dev server in these scripts. This allows each project to use its own separate version, which is webpack document Recommended version. If you want to use the global version, install it globally using npm install--global webpack and run it using the command webpack--config webpack.config.js.

When running the build command: npm run build

You should see some output from the webpack, starting with the following:

npm run build

> test-app@1.0.0 build C:\workspace\test-app
> node_modules/.bin/webpack --config webpack.config.js

Hash: 2b42bff7a022b5d956a9
Version: webpack 3.6.0
Time: 2002ms
                                        Asset       Size  Chunks                    Chunk Names
     Assets/Textures/NaturalEarthII/2/0/3.jpg    10.3 kB          [emitted]
                                       app.js     162 kB       0  [emitted]         app

The app.js package and the index.html file will be output to the dist folder.

Run the development server

Use webpack dev server service to develop and build, and then you can see our application in action:

npm install --save-dev webpack-dev-server

Add a start script in package.json to run the development server. Set the configuration file with the -- config flag. When executing the command, use the -- Open flag to open the application in the browser.

  "scripts": {
    "build": "node_modules/.bin/webpack --config webpack.config.js",
    "start": "node_modules/.bin/webpack-dev-server --config webpack.config.js --open"
  }

Tell the development server to provide files for the dist folder. Add it to the bottom of webpack.config.js.

    // development server options
    devServer: {
        contentBase: path.join(__dirname, "dist")
    }

Finally, we run the app

npm start

You should see your content rendered on localhost:8080 and a message displayed when "Hello World!" opens the browser console.

Add CesiumJS to a webpack app

Install CesiumJS

Install the cesium module from npmg and add it to package.json.

Configure CesiumJS in webpack configure CesiumJS in webpack

CesiumJS is a large and complex library. In addition to javascript modules, it also includes static assets, such as css, image and json files. It includes Web worker files to perform intensive computing in separate threads. Unlike traditional npm modules, CesiumJS does not define entry points because the library is used in a variety of ways. We need to configure some additional options to It is used with webpack.

First, define the location of CesiumJS. This tutorial is based on source code, so the webpack can contain a single model and track dependencies. Alternatively, you can use the built-in (simplified or unsimplified) version of CesiumJS. However, these modules have been combined and optimized, which gives us less flexibility.

Add the following code to the top of webpack.config.js:

// The path to the CesiumJS source code
const cesiumSource = 'node_modules/cesium/Source';
const cesiumWorkers = '../Build/Cesium/Workers';

This tutorial uses the npm module for ease of installation, but you can also clone it Github warehouse Download or unzip release version.

Add the following options to the configuration object to solve some problems with how webpack compiles CesiumJS.

    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),

        // Needed to compile multiline strings in Cesium
        sourcePrefix: ''
    },
    amd: {
        // Enable webpack-friendly use of require in Cesium
        toUrlUndefined: true
    },
    node: {
        // Resolve node module use of fs
        fs: 'empty'
    },
  • output.sourcePrefix: add a tab before each line to override the webpack default. CesiumJS has some multiline strings, so we need to override this default with an empty prefix '' *.
  • amd.toUrlUndefined: true   Tell CesiumJS AMD webpack to evaluate the version of the require statement using a non-conforming toUrl function.
  • node.fs: 'empty'   Solve some third-party use problems of FS module. The goal of this module is to use it in the node environment, not in the browser.

Add cesium   alias so that we can reference it in the application code.

    resolve: {
        alias: {
            // CesiumJS module name
            cesium: path.resolve(__dirname, cesiumSource)
        }
    },

Manage CesiumJS static files manages static files in CesiumJS

Finally, ensure that the static cesium JS assets, widgets, and web worker files are properly serviced and loaded.

As part of the build process, use copy webpack plugin to copy the static files to the dist directory.

npm install --save-dev copy-webpack-plugin

stay   The upper entry in the webpack.config.js file:

const CopywebpackPlugin = require('copy-webpack-plugin');

And add it to the plugins array:

    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        }),
        // Copy Cesium Assets, Widgets, and Workers to a static directory
        new CopywebpackPlugin([ { from: path.join(cesiumSource, cesiumWorkers), to: 'Workers' } ]),
        new CopywebpackPlugin([ { from: path.join(cesiumSource, 'Assets'), to: 'Assets' } ]),
        new CopywebpackPlugin([ { from: path.join(cesiumSource, 'Widgets'), to: 'Widgets' } ])
    ],

This copies the Assets and Widgets directories and the web worker scripts for build.

If you are using the fork of the cesium JS repository, the Build folder will not exist. Run npm run release to generate the output folder. For more information, see Cesium generation Guide.

Define an environment variable that tells CesiumJS to use webpackDefinePlugin to load the basic URL of the static file. The plugins array will now look like this:

    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        }),
        // Copy Cesium Assets, Widgets, and Workers to a static directory
        new CopywebpackPlugin([ { from: path.join(cesiumSource, cesiumWorkers), to: 'Workers' } ]),
        new CopywebpackPlugin([ { from: path.join(cesiumSource, 'Assets'), to: 'Assets' } ]),
        new CopywebpackPlugin([ { from: path.join(cesiumSource, 'Widgets'), to: 'Widgets' } ]),
        new webpack.DefinePlugin({
            // Define relative base path in cesium for loading assets
            CESIUM_BASE_URL: JSON.stringify('')
        })
    ],

Require CesiumJS modules in our app

In our application, there are several ways to reference the cesium JS module. You can use common JS syntax or ES6 import statements.

You can import the entire cesium JS library, or just import the specific modules you need. Introducing modules will cause webpack to compile only those modules and their dependencies in the package, not the entire library.

CommonJS style require

Introduce all CesiumJS:

var Cesium = require('cesium/Cesium');
var viewer = new Cesium.Viewer('cesiumContainer');

Introduction of independent modules

var Color = require('cesium/Core/Color');
var color = Color.fromRandom();

ES6 style import

Introduce all CesiumJS:

import Cesium from 'cesium/Cesium';
var viewer = new Cesium.Viewer('cesiumContainer');

Introduction of independent modules

import Color from 'cesium/core/Color';
var color = Color.fromRandom();

Requiring asset files references an asset file

The principle behind webpack is that each file is treated as a module. This makes importing assets the same as including javascript. We tell webpack how to use the loader to load each type of file in the configuration, so we only need to call require.

require('cesium/Widgets/widgets.css');

Hello World!

Create a new file, src/css/main.css, to style our application:

html, body, #cesiumContainer {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

Create a div for index.html   CesiumJS Viewer in body. replace

Hello World!

Use the following div:

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

Delete the content in index.js and include Cesium and our CSS file:

var Cesium = require('cesium/Cesium');
require('./css/main.css');
require('cesium/Widgets/widgets.css');

Add a line of code to create the Viewer:

var viewer = new Cesium.Viewer('cesiumContainer');

Run the application using npm start to view the Viewer in the browser.

Copy and paste your favorite Sandcastle example. For example, Particle system instance A good conclusion can be drawn.

Advanced webpack configurations

webpack can improve performance, reduce packet size, and perform other or complex build steps in more ways. Here, we will discuss some configuration options related to using the cesium JS library.

The configuration for optimizing the production Cesium webpack build can be found in the warehouse example of webpack.release.config.js.

Code splitting

By default, webpack packages CesiumJS in the same block as our application to generate a large file. We can split CesiumJS into our own packages and use common chunks plugin to improve the performance of our applications. If you end up creating multiple blocks for your application, they can all refer to a common cesium block.

Add the plug-in to the webpack.config.js file and specify the rules for decomposing the CesiumJS module:

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'cesium',
            minChunks: module => module.context && module.context.indexOf('cesium') !== -1
        })
    ]

Enable source maps enable source mapping

Source mapping allows Webpack to trace errors back to the original content. They provide more or less detailed debugging information in exchange for compilation speed. We recommend using the 'eval' option.

    devtool: 'eval'

Source mapping is not recommended in production products.

Remove pragmas remove compilation directives

There are developer errors and warnings in CesiumJS source code, which have been removed from our small release. Since there is no built-in Webpack method to remove these warnings, we will use strip pragma loader.

Installation package:

npm install strip-pragma-loader --save-dev

Set debug to false in module.rules and introduce the loader:

    rules: [{
        // Strip cesium pragmas
        test: /\.js$/,
            enforce: 'pre',
            include: path.resolve(__dirname, cesiumSource),
            use: [{
                loader: 'strip-pragma-loader',
                options: {
                    pragmas: {
                        debug: false
                    }
                }
            }]
    }]

Uglify and minify obfuscation and compression

Adding, deleting, and shrinking code allows smaller file sizes to be used in production. For a release, CesumJS modifies the JavaScript file and shrinks the CSS file.

Use uglifyjs webpack plugin to confuse the cesium JS source code.

npm install uglifyjs-webpack-plugin --save-dev

Introduce him in the configuration file:

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

Include him in the plug-in list:

    plugins: [
        new webpack.optimize.UglifyJsPlugin()
    ]

Use the minimize option on CSS loader to optimize CSS.

    module: {
        rules: [{
            test: /\.css$/,
            use: [
                'style-loader',
                {
                    loader: 'css-loader',
                    options: {
                        // minify loaded css
                        minimize: true
                    }
                }
            ]
        }]
    }

Resources resources

Official cesium-webpack-example The repository contains the minimum webpack configuration, the Hello World code described in this tutorial, and instructions for optional code configurations.

For a tutorial on the CesiumJS functionality to be included in the new application, see Cesium Workshop tutorial.

Explore examples in [Sandcastle] and view CesiumJS documentation

To learn more about webpack, see webpack concept , or Read the document in depth.

Cesium Chinese network QQ group: 838036184

Posted by cosmos33 on Wed, 20 Oct 2021 18:53:05 -0700