使用Webpack在全局引用中包含外部脚本 [英] Including external scripts with global references using Webpack

查看:315
本文介绍了使用Webpack在全局引用中包含外部脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Webpack 2打包一些较旧的javascript代码.该代码使用Leaflet 1.0库,还包含一个Leaflet插件(名为Google.js),该插件仅引用了Leaflet公开的全局L变量.

I am working on using Webpack 2 to package some oldish javascript code. This code uses the Leaflet 1.0 library and also includes a Leaflet plugin (named Google.js) that simply references the global L variable that leaflet exposes.

在当前的html页面中,先加载传单,然后加载插件(Google.js),然后再通过脚本标签加载map1.js代码.一切正常.

In the current html page, leaflet and then the plugin (Google.js) is loaded and then the map1.js code via script tags. Which all works fine.

我创建了以下webpack.config.js:

var path = require('path');

module.exports = {
  devtool: 'cheap-eval-source-map',
  entry: {
    map1: './js/map1.js'
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

,并且在map1.js中,我添加了以下内容来定义webpack的依赖关系要求:

and in the map1.js I have added the following to define the dependency requirements for webpack:

import bootstrap from 'bootstrap';
import leaflet from 'leaflet';
require('script-loader!./lib/Google.js');

bundle.js的构建没有问题,但是在页面加载时,我得到了:

The bundle.js builds without issue however when the page loads, I get:

Uncaught TypeError: Cannot read property 'call' of undefined
    at NewClass.whenReady (eval at  (bundle.js:79), :3641:12)
    at NewClass.addLayer (eval at  (bundle.js:79), :4057:8)
    at eval (eval at  (bundle.js:176), :118:7)
    at eval (eval at  (bundle.js:176), :232:3)
    at Object. (bundle.js:176)
    at __webpack_require__ (bundle.js:20)
    at bundle.js:66
    at bundle.js:69

查看发生错误的第79行:

Looking at line 79 where the errors occurs:

eval("var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*\n Leaflet 1.0.3, a JS library for interactive maps...

它似乎在评估单张代码时失败.我应该做其他任何事情来将Leaflet合并到我的webpack版本中吗?

it appears to failing on doing an eval of the leaflet code. Should I be doing anything else to incorporate Leaflet into my webpack build?

推荐答案

我刚刚使用 Leaflet.GridLayer.GoogleMutant 代替,它的工作原理就像一种魅力:

I just tried a very simple webpack project using Leaflet.GridLayer.GoogleMutant instead, and it works like a charm:

import 'leaflet';
import 'leaflet.gridlayer.googlemutant';

var map = L.map('map').setView([0,0],0);
var roadMutant = L.gridLayer.googleMutant({                     
  maxZoom: 24,                  
  type:'roadmap'                
}).addTo(map);

只要您在HTML的单独<script>中引用GMaps JS API,此方法就可以使用.还有npm install leaflet leaflet.gridlayer.googlemutant当然.

That will work as long as you reference the GMaps JS API in a separate <script> in your HTML. And npm install leaflet leaflet.gridlayer.googlemutant, of course.

这篇关于使用Webpack在全局引用中包含外部脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆