1 year ago

#365981

test-img

straylightrunner

How to code split Map component in react-map-gl?

I'm trying to codesplit a react-map-gl Map component into its own chunk using Lazy,Suspense.

This is my component.

import 'mapbox-gl/dist/mapbox-gl.css'
import React, {lazy, Suspense} from 'react'
const Map = lazy(() => import('react-map-gl'))

const MAPBOX_TOKEN = process.env.REACT_APP_MAPBOX_TOKEN
const MAP_STYLE = process.env.REACT_APP_MAPBOX_STYLE_DARK

export default function MapboxMap() {

    const viewport = {
        latitude: 37.805,
        longitude: -122.447,
        zoom: 15.5
    }

    return <div style={{width: '500px', height: '500px', position: 'relative'}}>
        <Suspense fallback={<div>Loading...</div>}>
            <Map
                initialViewState={viewport}
                mapboxAccessToken={MAPBOX_TOKEN}
                mapStyle={MAP_STYLE}
                styleDiffing
            />
        </Suspense>
    </div>
}

and this is my package.json

{
  "name": "compression-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-map-gl": "^7.0.10",
    "react-scripts": "^5.0.0"
  },
  "scripts": {
    "start": "react-scripts --openssl-legacy-provider start",
    "build": "react-scripts --openssl-legacy-provider build",
    "analyze": "source-map-explorer 'build/static/js/*.js'"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "source-map-explorer": "^2.5.2"
  }
}

But as you can see from the source-map-explorer screenshot, Mapbox is still in the main chunk.

Source Map Explorer

What am I doing wrong here? Has anyone else successfully tried to use the react-map-gl library and managed to split it into its own chunk?

mapbox-gl-js

mapbox-gl

react-map-gl

react-suspense

react-lazy-load

0 Answers

Your Answer

Accepted video resources