Skip to content

Instantly share code, notes, and snippets.

@ifandelse
Last active August 29, 2015 14:04
Show Gist options
  • Save ifandelse/0d37b816226fc219f26c to your computer and use it in GitHub Desktop.
Save ifandelse/0d37b816226fc219f26c to your computer and use it in GitHub Desktop.
Webpack Shim Question

In Require.js, it's possible to take a dependency on a "plain JS" lib (i.e. - it places a value on the window). For example, in the require.config, you'd do something along these lines:

  require.config({
      paths: {
        myAmdModule: "/path/to/my/amd/module",
        thirdPartyJS: "/path/to/plain/global/lib",
        jquery: "/path/to/jquery"
      },
      
      shim: {
        thirdPartyJS: {
          deps: ["jquery"],
          exports: "thirdPartyJS" // window.thirdPartyJS
        }
      }
  });
  
  //and then, in my main.js
  define(["thirdPartyJS", "myAmdModule"], function(thrirdPartyJS, myAmdModule){
    // while in many cases `thirdPartyJS` might exist on the window and a dev
    // could simply just reference window.thirdPartyJS, I prefer to keep dependencies
    // very explicit and discourage direct access of the window in these cases
  });

My question is - how do I duplicate this setup in webpack? At this point I'm not sure if I should be using externals, imports/exports loaders or DefinePlugin....

##Update This appears to work - is it the preferred approach, though?

define([
	"exports?thirdPartyJS!path/to/thirdPartyJS",
	"myAmdModule"
], function(thirdPartyJS, myAmdModule) {
   // module contents....
});

##Update 2 @sokra replied via gitter and gave me a much cleaner approach:

In my webpack.config.js file:

// showing only the relevant bits
module: {
  loaders: [
		{ test: "path/to/thirdPartyJS", loader: "exports?thirdPartyJS" }
	]
},
resolve: {
		alias: {
			thirdPartyJS : "path/to/thirdPartyJS"
		}
	}

And now, the AMD module looks the same as before (yay!):

define(["thirdPartyJS", "myAmdModule"], function(thrirdPartyJS, myAmdModule){
  // module contents
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment