You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PugJS中引入外部JavaScript文件并调用其函数?

如何在PugJS中引入外部Google Maps API相关JS文件并调用函数

我之前也碰到过一模一样的场景,用Express+Pug开发时想把Google Maps的逻辑抽离到独立JS文件里,其实只要搞定静态文件配置和脚本加载顺序这两个关键点就行,下面一步步给你拆解:


1. 先配置Express的静态文件目录

Express默认不会允许直接访问项目里的文件,所以得先告诉它哪些目录是公开可访问的。一般我们会把静态资源(JS、CSS、图片)放在项目根目录的public文件夹里:

// 你的app.js或server.js文件
const express = require('express');
const app = express();

// 关键:配置静态文件目录,这样public下的文件可以通过根路径直接访问
app.use(express.static('public'));

// 继续你的其他配置,比如设置Pug为模板引擎
app.set('view engine', 'pug');
app.set('views', './views');

// ... 其他路由和监听逻辑

2. 创建你的Google Maps工具JS文件

在public/js目录下新建一个文件,比如google-maps-utils.js,把所有和Google Maps相关的函数都写在这里。这里分两种写法,看你习惯哪种:

写法一:全局函数(无需模块导入,适合简单场景)

把函数挂在window对象上,这样在Pug页面里可以直接调用:

// public/js/google-maps-utils.js
// 初始化地图函数
window.initMap = function(mapElementId) {
  return new google.maps.Map(document.getElementById(mapElementId), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
};

// 添加标记函数
window.addMarker = function(map, markerPosition) {
  return new google.maps.Marker({
    position: markerPosition,
    map: map,
  });
};

写法二:ES模块(更规范,避免全局污染)

用export导出函数,需要在引入时指定type="module":

// public/js/google-maps-utils.js
export function initMap(mapElementId) {
  return new google.maps.Map(document.getElementById(mapElementId), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

export function addMarker(map, markerPosition) {
  return new google.maps.Marker({
    position: markerPosition,
    map: map,
  });
}

3. 在Pug模板中引入并调用函数

这里核心要注意脚本加载顺序:必须先加载Google Maps API,再加载你的工具JS,最后调用函数(因为你的函数依赖google对象)。

对应全局函数写法的Pug代码

// views/index.pug
html
  head
    title Google Maps Demo
    // 1. 先加载Google Maps API,替换成你自己的API_KEY,指定回调函数
    script(src="https://maps.googleapis.com/maps/api/js?key=你的API_KEY&callback=initApp")
    // 2. 加载你的工具JS
    script(src="/js/google-maps-utils.js")
  body
    // 地图容器
    #map(id="map-container" style="width: 100%; height: 400px;")
    // 3. 写页面初始化逻辑,作为Google Maps的回调
    script.
      function initApp() {
        // 直接调用工具JS里的全局函数
        const map = initMap('map-container');
        // 添加一个标记
        addMarker(map, { lat: -34.397, lng: 150.644 });
      }

对应ES模块写法的Pug代码

需要给脚本标签加上type="module":

// views/index.pug
html
  head
    title Google Maps Demo
    // 1. 加载Google Maps API,不用指定callback,后面自己监听加载状态
    script(src="https://maps.googleapis.com/maps/api/js?key=你的API_KEY")
  body
    #map(id="map-container" style="width: 100%; height: 400px;")
    // 2. 用module类型加载你的工具JS,并写初始化逻辑
    script(type="module").
      import { initMap, addMarker } from '/js/google-maps-utils.js';
      
      // 等待Google Maps加载完成
      function waitForGoogleMaps() {
        return new Promise(resolve => {
          if (window.google) {
            resolve();
          } else {
            setTimeout(() => waitForGoogleMaps().then(resolve), 100);
          }
        });
      }
      
      // 初始化应用
      async function initApp() {
        await waitForGoogleMaps();
        const map = initMap('map-container');
        addMarker(map, { lat: -34.397, lng: 150.644 });
      }
      
      initApp();

几个关键注意事项

  • 别忘替换你的API_KEY:去Google Cloud控制台申请有效的Maps API密钥,否则地图加载不出来。
  • 静态文件路径要正确:如果你的工具JS在public/js/google-maps-utils.js,那么Pug里的引入路径就是/js/google-maps-utils.js(因为Express把public作为根路径)。
  • 确保Google Maps先加载完成:不管用callback还是Promise等待,都要保证google对象存在后再调用你的工具函数,否则会报错。

内容的提问来源于stack exchange,提问作者Sam T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:53:37