在TypeScript中使用MapLibre-GL报错“require未定义”求解决方案
问题解决:TypeScript使用MapLibre地图时
Uncaught ReferenceError: require is not defined 错误原因
你在script.ts中使用了ES模块的import语法,但TypeScript默认将代码编译为CommonJS模块规范,导致生成的script.js中包含浏览器原生不支持的require函数,从而触发错误。
解决方案
方案1:使用全局变量(无需打包,适配CDN场景)
- 安装MapLibre的TypeScript类型定义,解决TS类型校验报错:
npm install @types/maplibre-gl --save-dev - 修改
script.ts,直接使用CDN注入的全局变量maplibregl(注意CDN引入的全局变量名称是maplibregl,而非你代码中的MapLibreGL):const map = new maplibregl.Map({ container: 'map', style: 'https://demotiles.maplibre.org/style.json', center: [0, 0], zoom: 1 }); - 调整
tsconfig.json的module配置,避免生成模块相关代码:{ "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false, "sourceMap": true, "target": "es5", "esModuleInterop": true, "module": "None" }, "exclude": [ "node_modules" ] } - 重新编译TypeScript代码,浏览器运行即可正常加载地图。
方案2:使用ES模块(现代前端开发方式)
- 安装MapLibre核心库及类型定义:
npm install maplibre-gl @types/maplibre-gl --save-dev - 修改
index.html,将脚本引入标记为ES模块,同时替换MapLibre的CDN为ES模块版本:<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@3.3.1/dist/maplibre-gl.css' /> <!-- 替换原有脚本引入 --> <script type="module" src="script.js"></script> - 更新
tsconfig.json,配置为ES模块规范:{ "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false, "sourceMap": true, "target": "esnext", "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler" }, "exclude": [ "node_modules" ] } - 若不想使用打包工具,可直接在
script.ts中从CDN导入模块:import maplibregl from 'https://unpkg.com/maplibre-gl@3.3.1/dist/maplibre-gl.esm.js'; const map = new maplibregl.Map({ container: 'map', style: 'https://demotiles.maplibre.org/style.json', center: [0, 0], zoom: 1 }); - 若使用打包工具(如Vite、Webpack),则保留原
import语法即可,打包工具会处理模块依赖。
内容的提问来源于stack exchange,提问作者MetaMapper
相关产品推荐
相关产品推荐

