Module 04 - The npm + Vite Project
Level 1 · Your First Maps · 🟢 Beginner · 3 hours · Prereq: Module 03
What you'll build
The same map as Module 03, but as a real project: npm, Vite, ES modules, environment
variables, and a production build you can measure. Then you will look at what the bundler
produced and understand why it is 400 KB and not 40 MB.
This project shape is what every remaining module and challenge uses.
Why this matters
Every professional SDK application is bundled. That buys you:
- Tree shaking - you ship the 5% of the SDK you import
- Version control -
package-lock.jsonpins exactly what runs - Offline development - no CDN dependency
- Secrets handling - API keys via environment, not source
- Framework integration - React, Vue, Angular all assume a bundler
- Type checking - the SDK ships full TypeScript definitions
It also introduces a class of problems that don't exist on the CDN: asset paths, worker files, chunk splitting, and dev-server pre-bundling. Meeting them now, in a 40-line app, is much cheaper than meeting them in a 4,000-line one.
Concepts
1. What a bundler does with @arcgis/core
@arcgis/core on disk is roughly 400 MB and tens of thousands of files. Your bundle is a few
hundred KB. The difference is the import graph.
your main.js
├── imports Map.js
│ └── imports Basemap.js → LayerList collection → Accessor …
├── imports MapView.js
│ └── imports the 2D renderer, WebGL, tile handling …
└── imports ScaleBar.js
Everything NOT reachable from these roots is dropped.
Import SceneView and you pull in the entire 3D engine. Import Sketch and you pull in the
geometry editing stack. Your bundle size is a direct function of your import list, which is
why Module 40 starts with "read your imports."
2. Vite's two modes
npm run dev |
npm run build |
|
|---|---|---|
| Bundler | esbuild pre-bundle + native ESM | Rollup |
| Your code | Served unbundled, per-file | Bundled, minified, split |
| Dependencies | Pre-bundled once into node_modules/.vite |
Tree-shaken into chunks |
| First start | Slow (~30-60 s for the SDK) | - |
| Rebuild | Instant (HMR) | Full |
The first npm run dev after installing the SDK is slow. esbuild is converting thousands
of SDK modules into a handful of pre-bundled files. This is cached; subsequent starts are fast.
If it re-bundles every time, something is invalidating the cache - usually a changed
optimizeDeps config or a node_modules touch.
3. Where the SDK's non-JS assets live
The SDK needs runtime files that are not JavaScript:
- Icon fonts and images for widgets
- Web workers for tile decoding and geometry tessellation
- WASM for geometry operators and projection engine
- Localisation strings (
t9n)
Vite and modern bundlers resolve these from @arcgis/core/assets automatically. When they
don't - some Webpack configs, some CDN deployments, some sub-path hostings - you set:
import esriConfig from "@arcgis/core/config.js";
esriConfig.assetsPath = "https://js.arcgis.com/5.0/@arcgis/core/assets";
Symptom of a broken assets path: widgets show empty boxes where icons should be, or the
console shows 404s under /assets/esri/. Module 43 covers deploying assets properly.
4. Environment variables in Vite
.env.local # git-ignored, your real values
.env.example # committed, documents what's needed
VITE_ARCGIS_API_KEY=AAPT...
const apiKey = import.meta.env.VITE_ARCGIS_API_KEY;
Three rules:
- Only
VITE_-prefixed variables are exposed to client code. This is a guardrail against leaking server secrets into a bundle. - They are inlined at build time, not read at runtime. Changing
.env.localrequires a dev server restart. - They are not secret. They end up in the JavaScript any user can read. An API key here is protected by referrer rules and privilege scoping, not by obscurity. (Module 39.)
Build it
Step 1 - Scaffold
npm create vite@latest webgis-m04 -- --template vanilla
cd webgis-m04
npm install
npm install @arcgis/core
--template vanilla gives plain JS with no framework. React comes in Module 37.
npm install @arcgis/core takes a while and writes ~400 MB. That is expected.
Step 2 - Clean the template
Delete counter.js, javascript.svg, and the contents of style.css.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>Web GIS - Module 04</title>
</head>
<body>
<div id="viewDiv"></div>
<div id="panel">
<h1>Module 04</h1>
<p id="status">Loading…</p>
</div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
src/style.css:
@import "@arcgis/core/assets/esri/themes/light/main.css";
html, body { margin: 0; padding: 0; height: 100%; }
#viewDiv { position: absolute; inset: 0; }
#panel {
position: absolute;
top: 16px; right: 16px;
z-index: 10;
width: 240px;
padding: 14px 16px;
background: #fff;
border-radius: 10px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.18);
font: 14px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
}
#panel h1 { margin: 0 0 8px; font-size: 15px; }
#panel p { margin: 0; color: #555; }
The @import line is the npm equivalent of the CDN's <link>. Vite resolves
@arcgis/core/assets/... from node_modules and inlines it into your CSS bundle.
Some setups prefer
import "@arcgis/core/assets/esri/themes/light/main.css";in JS instead. Both work. CSS-side@importkeeps all styling concerns in one file; JS-side import makes the dependency visible to anyone readingmain.js. Pick one and be consistent.
Note position: absolute; inset: 0 on #viewDiv - this sidesteps the height: 100% chain
entirely. It is the more robust pattern for app layouts.
Step 3 - Environment
.env.example (commit this):
VITE_ARCGIS_API_KEY=your_key_here
.env.local (do NOT commit):
VITE_ARCGIS_API_KEY=AAPT...your actual key...
.gitignore - confirm it contains:
node_modules
dist
*.local
.env
.env.local
Vite's default .gitignore already has *.local, which covers .env.local. Verify, don't
assume - a leaked key with routing privileges costs real money.
Step 4 - src/main.js
import "./style.css";
import esriConfig from "@arcgis/core/config.js";
import Map from "@arcgis/core/Map.js";
import MapView from "@arcgis/core/views/MapView.js";
import Graphic from "@arcgis/core/Graphic.js";
import ScaleBar from "@arcgis/core/widgets/ScaleBar.js";
import Home from "@arcgis/core/widgets/Home.js";
// Fail loudly and immediately rather than showing a mysterious grey map.
const apiKey = import.meta.env.VITE_ARCGIS_API_KEY;
if (!apiKey) {
throw new Error(
"VITE_ARCGIS_API_KEY is not set. Copy .env.example to .env.local, add your key, " +
"and restart the dev server (Vite reads env only at boot)."
);
}
esriConfig.apiKey = apiKey;
const map = new Map({ basemap: "arcgis/navigation" });
const view = new MapView({
container: "viewDiv",
map,
center: [-76.481, 44.231],
zoom: 13,
});
view.ui.add(new ScaleBar({ view, unit: "metric" }), "bottom-left");
view.ui.add(new Home({ view }), "top-left");
view.graphics.add(
new Graphic({
geometry: { type: "point", longitude: -76.4813, latitude: 44.2312 },
symbol: {
type: "simple-marker",
color: [0, 102, 255, 0.9],
size: 14,
outline: { color: "white", width: 2 },
},
attributes: { name: "Kingston City Hall", built: 1844 },
popupTemplate: { title: "{name}", content: "Built in {built}." },
})
);
const status = document.getElementById("status");
view
.when()
.then(() => {
status.textContent = `Ready · WKID ${view.spatialReference.wkid}`;
})
.catch((error) => {
status.textContent = `Failed: ${error.message}`;
console.error(error);
});
Three things changed from Module 03, and each is deliberate:
- Bare import specifiers.
"@arcgis/core/Map.js"instead of a full URL. Vite resolves it fromnode_modules. - The env guard throws. A missing key otherwise produces a grey map and a 403 buried in the network tab. Throwing at line 12 with a message that says what to do is a kindness to your future self and to anyone who clones the repo.
view.when()used as a Promise, with.catch(). Same thing as Module 03's two-callback form, but composable.
Step 5 - Run it
npm run dev
First run: 30-60 seconds of "Optimizing dependencies…". After that, sub-second.
Verify:
- Map renders
- Panel shows
Ready · WKID 3857 - Popup works on the marker
- No console errors
Then edit the center and watch HMR update without a full reload.
Step 6 - Build and measure
npm run build
Read the output carefully. You'll see something like:
dist/index.html 0.51 kB │ gzip: 0.33 kB
dist/assets/index-a1b2c3d4.css 128.42 kB │ gzip: 18.90 kB
dist/assets/index-e5f6g7h8.js 843.17 kB │ gzip: 231.44 kB
Then:
npm run preview
Now do the experiment. Add this import to main.js:
import SceneView from "@arcgis/core/views/SceneView.js";
Don't use it - just import it. Build again.
The bundle grows by roughly 500 KB. You imported the entire 3D rendering engine by writing one line. This is the single most important lesson of the module: in this SDK, imports are expensive and the cost is invisible until you measure it.
Remove the import and rebuild to confirm it goes back down.
Step 7 - Add a bundle visualiser
npm install -D rollup-plugin-visualizer
vite.config.js:
import { defineConfig } from "vite";
import { visualizer } from "rollup-plugin-visualizer";
export default defineConfig({
plugins: [
visualizer({
filename: "dist/stats.html",
gzipSize: true,
brotliSize: true,
}),
],
});
npm run build && npx serve dist
Open stats.html. You now have a treemap of exactly what is in your bundle.
Look for:
- How much is
@arcgis/corevs your code (spoiler: 99% vs 1%) - Which SDK subtrees are largest -
views/2d,geometry,widgets - What you're pulling in that you didn't expect
Keep this plugin in every project you build during this course. You will use it in Module 40.
Step 8 - Manual chunking (optional but instructive)
One 850 KB JavaScript file is a poor loading experience. Split it:
// vite.config.js
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes("@arcgis/core/views/3d")) return "arcgis-3d";
if (id.includes("@arcgis/core/widgets")) return "arcgis-widgets";
if (id.includes("@arcgis/core")) return "arcgis-core";
},
},
},
},
});
Rebuild. You now have three cacheable chunks instead of one monolith. When you change your app code, users re-download only your chunk, not the SDK.
Why this matters more than it looks: the SDK chunk's content hash doesn't change between your deploys. A returning user downloads 0 bytes of ArcGIS. Getting this right is worth more than most micro-optimisations.
How it works
Why the dev server pre-bundles
Native ESM in the browser means one HTTP request per module. @arcgis/core has tens of
thousands. Even locally, 30,000 requests takes minutes and hits Chrome's connection limits.
esbuild pre-bundles each dependency into a single file, so the browser requests
node_modules/.vite/deps/@arcgis_core_Map__js.js once. Your own source stays unbundled, which
is what makes HMR instant.
Why tree shaking works on this SDK at all
Three properties make it possible:
"sideEffects": falsein@arcgis/core'spackage.json- tells the bundler that dropping an unused module cannot break anything.- One class per file - the unit of elimination is fine-grained.
- Static
importstatements - the graph is analysable without running the code.
Break any of these and it stops working. This is why import * as everything from "..." and
runtime-computed dynamic imports defeat tree shaking.
Why import.meta.env and not process.env
process is a Node global; it does not exist in a browser. Vite exposes import.meta.env -
part of the ES module spec - and statically replaces import.meta.env.VITE_FOO with a string
literal at build time.
Consequence worth internalising: you cannot do import.meta.env[dynamicKey]. The
replacement is textual. It has to be a literal property access.
What esriConfig actually is
A singleton module of global settings, read by the SDK at request time:
esriConfig.apiKey // default credential for Esri services
esriConfig.assetsPath // where widget icons/workers/wasm come from
esriConfig.request.timeout // ms before a request gives up
esriConfig.request.interceptors // modify every outgoing request (Module 39)
esriConfig.portalUrl // default portal for portalItem lookups
esriConfig.log.level // "info" | "warn" | "error" | "none"
Because it is read at request time, set it before the first request. Setting apiKey
after the view has already asked for a basemap does nothing for that request.
Common mistakes
Editing .env.local and not restarting the dev server.
Vite reads env at boot. Your change did nothing. Restart.
Committing .env.local.
Check git status before your first commit. If you've already pushed a key, revoke it in the
dashboard immediately - rotating is cheap, a compromised routing key is not.
Importing from "@arcgis/core/Map" without .js.
Sometimes works via bundler resolution, breaks under strict ESM and in some Node tooling. Use
the extension.
Mixing @arcgis/core (npm) and js.arcgis.com (CDN) imports.
Two SDK instances, two esriConfig globals, failing instanceof checks. Pick one.
Ignoring the "chunks are larger than 500 kB" warning. Vite is telling you something true. Either chunk it (Step 8) or consciously accept it and write down why.
Importing a widget you only use conditionally.
// ❌ always in the bundle
import Sketch from "@arcgis/core/widgets/Sketch.js";
if (userCanEdit) new Sketch({ view });
// ✅ only downloaded when needed
if (userCanEdit) {
const { default: Sketch } = await import("@arcgis/core/widgets/Sketch.js");
new Sketch({ view });
}
This repo uses exactly that pattern throughout src/components/viewer/Sidebar/tools/.
Exercises
Exercise 04.1 - Measure five imports
Starting from your working build, measure the bundle size after each addition. Build fresh each time and record the gzipped JS size.
| Added import | Size | Delta |
|---|---|---|
| baseline (Map + MapView + ScaleBar + Home) | - | |
+ @arcgis/core/layers/FeatureLayer.js |
||
+ @arcgis/core/widgets/Legend.js |
||
+ @arcgis/core/views/SceneView.js |
||
+ @arcgis/core/widgets/Sketch.js |
||
+ @arcgis/core/geometry/operators/bufferOperator.js |
Rank them by cost. Which surprised you? Keep this table - it will inform architecture decisions for the rest of the course.
Exercise 04.2 - Config injection
Refactor so the map's centre, zoom and basemap come from environment variables with sensible defaults:
const config = {
center: [
Number(import.meta.env.VITE_MAP_LON ?? -76.481),
Number(import.meta.env.VITE_MAP_LAT ?? 44.231),
],
zoom: Number(import.meta.env.VITE_MAP_ZOOM ?? 13),
basemap: import.meta.env.VITE_BASEMAP ?? "arcgis/navigation",
};
Then: why is Number(...) necessary? What happens without it? (Try it - pass zoom as a
string and see what the view does.)
Exercise 04.3 - Break the assets path
Add esriConfig.assetsPath = "/nonexistent" and build. Observe:
- What still works
- What visually breaks
- What the Network tab shows
Then fix it by pointing at the CDN assets. This is a real deployment failure mode and you want to have seen it once.
Exercise 04.4 - TypeScript (optional, recommended)
Rename main.js to main.ts and add typescript as a dev dependency. The SDK ships full
types, so you immediately get:
- Autocomplete on every property
- Errors on typos like
zomm: 13 - Signature help on
queryFeatures
Fix the type errors that appear. Even if you stay on JavaScript for the course, spending 30 minutes here shows you how much the type definitions know - and VS Code will use them for JS autocomplete anyway.
Checkpoint
- Why is the first
npm run devslow, and why is the second one fast? - Adding one unused
import SceneViewgrew the bundle by 500 KB. Why? - What makes
VITE_ARCGIS_API_KEYavailable in the browser butDATABASE_URLnot? - What is
esriConfig.assetsPathfor, and what breaks when it's wrong? - Why must
esriConfig.apiKeybe set before creating the map? - Name two things that defeat tree shaking.
- First run, esbuild pre-bundles thousands of SDK modules into
node_modules/.vite. That cache persists, so later starts skip the work. - Tree shaking is based on the static import graph. Importing
SceneViewmakes the entire 3D renderer reachable, and reachable code is kept - the bundler cannot prove you won't construct one. - Vite only inlines variables prefixed
VITE_. It's a deliberate guardrail so server secrets in the same.envdon't leak into client code. - It tells the SDK where to fetch widget icons, localisation, web workers and WASM at runtime.
Wrong path → 404s under
/assets/esri/, blank widget icons, and geometry operators that fail to load. esriConfigis read at request time. The view requests the basemap almost immediately; if the key isn't set yet, that request goes out unauthenticated and 403s.- Namespace imports (
import * as x), runtime-computed dynamic import paths, side-effectful modules not markedsideEffects: false, and top-level code with observable effects.
Further reading
- https://developers.arcgis.com/javascript/latest/get-started-npm/ - Esri's npm guide
- https://vitejs.dev/guide/env-and-mode.html - Vite env handling in full
- https://developers.arcgis.com/javascript/latest/tooling-intro/ - build tooling per bundler, including Webpack and Angular CLI specifics