Skip to content

Commit

Permalink
Load OL as modules using an import map instead of from a bundle
Browse files Browse the repository at this point in the history
The OL modules can be loaded from unpkg if a version other than the one
in package.json is specified

Also added an option in the benchmarks to select another OL version (only
versions above 9.0 are supported)
  • Loading branch information
jahow committed Jan 5, 2025
1 parent b66cbba commit 5050aaa
Show file tree
Hide file tree
Showing 8 changed files with 198 additions and 0 deletions.
18 changes: 18 additions & 0 deletions cases/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,24 @@ function animate() {
}

export function initializeGui() {
// @ts-ignore
const olVersion =
new URL(window.location.href).searchParams.get('olVersion') ??
// @ts-ignore
// eslint-disable-next-line no-undef
__DEFAULT_OL_VERSION; // defined at build time by Vite
gui
.add({olVersion}, 'olVersion')
.name('OpenLayers Version')
// @ts-ignore
// eslint-disable-next-line no-undef
.options(__OL_VERSIONS) // defined at build time by Vite
.onFinishChange((/** @type {string} */ rawValue) => {
const newUrl = new URL(window.location.href);
newUrl.searchParams.set('olVersion', rawValue);
window.location.href = newUrl.href;
});

registerGuiParameter('animate', 'Start Animation', [], animate, () => {});
registerGuiParameter(
'renderer',
Expand Down
83 changes: 83 additions & 0 deletions cases/create-importmap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
const currentUrl = new URL(window.location.href);
const olVersion = currentUrl.searchParams.get('olVersion');

if (document.currentScript) {
const importMap = document.createElement('script');
importMap.type = 'importmap';

const commonImports = `
"color-rgba": "/node_modules/color-rgba/index.js",
"color-parse": "/node_modules/color-parse/index.js",
"color-name": "/node_modules/color-name/index.js",
"color-name/": "/node_modules/color-name/",
"color-space/": "/node_modules/color-space/",
"rbush": "/node_modules/rbush/index.js",
"quickselect": "/node_modules/quickselect/index.js",
"earcut": "/node_modules/earcut/src/earcut.js"`;

// this import map is used if we're asking for a specific version
if (olVersion) {
importMap.textContent = `
{
"imports": {
"ol/": "https://unpkg.com/ol@${olVersion}/",
"/node_modules/ol/": "https://unpkg.com/ol@${olVersion}/",
${commonImports}
}
}
`;
} else {
importMap.textContent = `
{
"imports": {
"ol/": "/node_modules/ol/",
${commonImports}
}
}
`;
}
document.currentScript.insertAdjacentElement('beforebegin', importMap);

// trying to import this module to make sure we have a chance of the Webgl renderer to work
import('ol/render/webgl/VectorStyleRenderer.js')
.then(() => {
// do nothing: it worked
})
.catch((error) => {
const withoutOlVersion = new URL(window.location.href);
withoutOlVersion.searchParams.delete('olVersion');

// show error in page
const errorBlock = document.createElement('div');
errorBlock.innerHTML = `
<p><strong>OpenLayers version "${
olVersion ?? 'unknown'
}" failed to load properly</strong></p>
<p>First make sure that the version specified is valid. If it is, try reloading the page a few times (the CDN might have timed out when fetching the library).</p>
<p><a href="${withoutOlVersion}">Click here to reload the page with the latest OpenLayers version (this should work!)</a></p>
<p><small>Error was: ${error.message}</small></p>
`;
errorBlock.style.cssText = `
background-color: rgb(255, 243, 205);
border: 1px solid rgb(255 235 175);
border-radius: 6px;
color: rgb(133, 100, 4);
font-family: "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
font-size: 16px;
padding: 12px 20px;
box-sizing: border-box;
width: 800px;
max-width: calc(100vw - 20px);`;
const container = document.createElement('div');
container.style.cssText = `
position: relative;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
`;
container.append(errorBlock);
document.body.append(container);
});
}
1 change: 1 addition & 0 deletions cases/filtering-shapes/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>Filtering Shapes</title>
<link rel="stylesheet" href="../../style.css">
<script src="../create-importmap.js"></script>
</head>

<body>
Expand Down
1 change: 1 addition & 0 deletions cases/line-rendering/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>Line Rendering</title>
<link rel="stylesheet" href="../../style.css">
<script src="../create-importmap.js"></script>
</head>

<body>
Expand Down
1 change: 1 addition & 0 deletions cases/point-rendering/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>Point Rendering</title>
<link rel="stylesheet" href="../../style.css">
<script src="../create-importmap.js"></script>
</head>

<body>
Expand Down
1 change: 1 addition & 0 deletions cases/polygon-rendering/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>Polygon Rendering</title>
<link rel="stylesheet" href="../../style.css">
<script src="../create-importmap.js"></script>
</head>

<body>
Expand Down
1 change: 1 addition & 0 deletions cases/vector-tiles-rendering/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>Vector Tiles Rendering</title>
<link rel="stylesheet" href="../../style.css">
<script src="../create-importmap.js"></script>
</head>

<body>
Expand Down
92 changes: 92 additions & 0 deletions vite.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import fs from 'fs/promises';
import {defineConfig} from 'vite';
import {dependencies} from './package.json';
import {existsSync, readdirSync} from 'fs';
import {join, resolve} from 'path';

Expand All @@ -15,12 +17,102 @@ for (const name of readdirSync(casesDir)) {
}
}

// this Vite plugin will put the import map before anything else to have it properly work in dev
const putImportmapFirst = () => ({
name: 'put-importmap-first',
transformIndexHtml(html) {
const importmapLine = html.match(/<script .+importmap.+<\/script>/)?.[0];
if (!importmapLine) {
return html;
}
return html.replace(importmapLine, '').replace(
'<head>',
`<head>
${importmapLine}`
);
},
});

// this Vite plugin will copy node_modules/ol and its dependencies to the assets at build time
const addNodeModulesToDist = () => {
return {
name: 'copy-ol-in-assets',
apply: 'build',
async writeBundle() {
const toCopy = [
['./node_modules/ol', './dist/node_modules/ol'],
['./node_modules/color-rgba', './dist/node_modules/color-rgba'],
['./node_modules/color-parse', './dist/node_modules/color-parse'],
['./node_modules/color-name', './dist/node_modules/color-name'],
['./node_modules/color-space', './dist/node_modules/color-space'],
['./node_modules/rbush', './dist/node_modules/rbush'],
['./node_modules/quickselect', './dist/node_modules/quickselect'],
['./node_modules/earcut', './dist/node_modules/earcut'],
// also copy the import map script
['./cases/create-importmap.js', './dist/cases/create-importmap.js'],
];
await Promise.all(
toCopy.map(([src, dest]) =>
fs.cp(src, dest, {
recursive: true,
})
)
);

// tweak color-name default export
const colorNamePath = './dist/node_modules/color-name/index.js';
const colorName = await fs.readFile(
'./dist/node_modules/color-name/index.js',
'utf-8'
);
await fs.writeFile(
colorNamePath,
colorName.replace('module.exports = ', 'export default ')
);
},
};
};

// list of supported OL versions and current one
const SUPPORTED_OL_VERSIONS = [
'10.3.1',
'10.3.0',
'10.2.1',
'10.2.0',
'10.1.0',
'10.0.0',
'9.2.4',
'9.2.3',
'9.2.2',
'9.2.1',
'9.2.0',
'9.1.0',
'9.0.0',
];
const CURRENT_OL_VERSION = dependencies.ol;

export default defineConfig({
plugins: [putImportmapFirst(), addNodeModulesToDist()],
build: {
rollupOptions: {
input,
output: {
esModule: true,
},
external: [/^ol\//],
},
},
define: {
// list of OL version as env
'__OL_VERSIONS': JSON.stringify([
CURRENT_OL_VERSION,
...SUPPORTED_OL_VERSIONS,
]),
'__DEFAULT_OL_VERSION': JSON.stringify(CURRENT_OL_VERSION),
},
optimizeDeps: {
noDiscovery: true,
},
esbuild: {
minifyIdentifiers: false,
},
Expand Down

0 comments on commit 5050aaa

Please sign in to comment.