javascript - Synchronous require in Webpack -
i'm using webpack , i'm using require pull in packages. have 2 packages: package1.js , package2.js. package1.js creates object properties called pkg1
. package2 javascript file contains self executing function extends package1. e.g.
package2.js:
!function () { pkg1.prototype.newfunction = function {return "foo"}; }()
i'm trying require both of these new script in following manner:
require('package1') require('package2')
when this, error:
uncaught typeerror: pkg1.newfunction not function
i think because of javascripts asynchronous loading: require(package2)
executes before require('package1')
. evidence when following don't error:
require('package1') !function () { pkg1.prototype.newfunction = function {return "foo"}; }()
however, messy, , use require. how go making work?
edit: specific examples
the leaflet-d3 plugin begins with:
(function() { l.hexbinlayer = l.class.extend({ ... })()
hence, @ least understanding, putting in require(leaflet-d3-plugin)
should cause script execute , extend l
brought in require('leaflet')
similarly, d3-hexbin-v0 starts with:
!function(){d3.hexbin=function(){ ... }}()
again, way read this script adds .hexbin
method d3
.
now if writing html, put these different things in various script tags , works:
<script src="http://d3js.org/d3.v3.min.js"></script> <script src="http://d3js.org/d3.hexbin.v0.min.js"></script>
or
<script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"></script> <script src="static/leaflet-d3.min.js" charset="utf-8"></script>
but since i'm using webpack, should able require and/or import these libraries after have installed them npm or if copy .js in these scripts directory , require
them location. unfortunately, not seem work unless copy .js in these modules directly whatever script writing. trying avoid.
e.g.
import * d3 'd3'; \\i'm using d3 v4 here. require('/resources/d3-hexbin.min.js')
results in:
uncaught typeerror: d3.hexbin not function
webpack loades synchronously each file have own scope.
that's why in statement
import * d3 'd3'; \\i'm using d3 v4 here. require('/resources/d3-hexbin.min.js')
your second doesn't find d3
variable.
you can solve using provideplugin
:
webpack.config.js
plugins: [ new webpack.provideplugin({ d3: 'd3' }), ... //other plugins
this way d3
available throughout application.
alternative way achieve use following:
import * d3 'd3'; window.d3 = d3; require('./d3.hexbin.v0.min.js')
hope helps you!
Comments
Post a Comment