Including external scripts with global references using Webpack

蓝咒 提交于 2019-12-12 02:37:59

问题


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.

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.

I have created the following 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')
  }
};

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');

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

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...

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?


回答1:


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);

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.



来源:https://stackoverflow.com/questions/42638423/including-external-scripts-with-global-references-using-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!