Using Cesium function in Web worker

I want to use the cesium’s process function and data types(like Cartisian3) in web worker.
I searched related topics in the community:

I tried to add cesium to the worker using import Cesium from ‘cesium’ , or importScripts(‘url_to_cesium_index.js’) . but none of them work.
So how to use Cesium functions in Web worker ?

1 Like

Hi,

There is no reason you can’t use Cesium functions in a web worker.

However, web workers do not share the same global scope as the webpage. You must import Cesium code accordingly, and any build process for workers may need to be treated differently that that of the main app.

Could you share the current way you are creating the worker and and built tools associated with your project? For example are you using webpack to build?

Thanks,
Gabby

1 Like

Yes,I use webpack and worker-loader to build the project,
1, Webpack rule config for worker-loader as below:

config.module.rules = [
      {
        test: /\.worker\.js$/i,
        use: [
          {
            loader: 'worker-loader',
            options: {
              inline: 'no-fallback'
            }
          }
        ]
      },
      ...config.module.rules
    ]

2, The web worker is implemented in “history-data.worker.js”:

import _ from 'lodash'
import moment from 'moment'
importScripts(`http://localhost/js/Cesium/index.js`)

self.onmessage = async function (e) {
  const type = e.data.type
  const payload = e.data.payload

  if (type === 'INIT') {
    console.log('init time', moment().format('YYYY-MM-DD HH:mm:ss.SSSS'))
    self.postMessage({
      type: 'WORKER_INIT',
      payload: { data: 'success' }
    })
  }
}

3, The worker is imported and created in the project:

   import DataWorker from './worker/history-data.worker'
   const dataProcessWorker = new DataWorker()
   const dataProcessWorker.postMessage({ type: 'INIT', payload: {} })

So could you please make an example of using Cesium in a web worker?
Thank you.

Hi there,

import * as Cesium from 'cesium' is the best way to import Cesium.

The issue is that webpack is not handling the optional chaining in the source code ( the variable.?property syntax). This issue should cover how to address the issue..

You can also import only the modules you need in the worker to help minimize the worker, for example

import { Cartesian3, Cartographic } from 'Cesium'.

Thank you, following you suggestion it works.

Add these lines to package.json, replace the acorn package that the webpack uses as a parser:

{
  ...
  "resolutions": {
    "acorn": "npm:acorn-with-stage3"
  },
  "dependencies": {