Search code examples
javascriptdependencieswebpackphysicsjs

Resolving external submodule dependences in webpack


I am trying to include a modular third-party library (PhysicsJS) into my webpack project. This library is AMD- and CommonJS-friendly, and has well-formed submodules that I want to access. However it is primarily structured for RequireJS, via its packages definition spec in require.config(), so the entry point isn't a standard index.js. Instead the entry point is physicsjs.js.

In other words, I can't seem to figure out how to configure webpack to resolve both the library's main file and its submodules. It just seems like if the library's entry point isn't index.js and it has submodules, you are out of luck, and I just can't believe that's correct, so I must be missing something.

So, how can the following statements be made to resolve?

require('physicsjs'); // entry point
require('physicsjs/bodies/rectangle');  // submodule

I have tried variations of this config:

resolve: {
    modulesDirectories: [
        'js/bower_components'
    ],
    alias: {
        'physicsjs': 'PhysicsJS/dist/',
        // doesn't find physicsjs.js

        'physicsjs': 'PhysicsJS/dist/physicsjs.js'
        // doesn't find the submodules
    }
},

The directory structure looks something like this:

+ js
  - main.js
  + bower_modules
    + PhysicsJS
      + dist
        - physicsjs.js // module entry point
        + bodies
          - rectangle.js // desired submodule
  + lib
    - MyModule.js

Note that PhysicsJS does have a minified version of the entire library, which I will use if there is no other alternative, but I would rather only load what I actually use.

Also, the submodules themselves use require('physicsjs'), so calling require('physicsjs/physicsjs') is not a solution.


Solution

  • The solution is to declare the alias twice, first as an exact match (using a trailing $) and then again as a normal match (no trailing $). So my config now looks more like this:

    resolve: {
        modulesDirectories: [
            'js/bower_components'
        ],
        alias: {
            'physicsjs$': 'PhysicsJS/dist/physicsjs.js', // Exact match
            'physicsjs': 'PhysicsJS/dist' // and again with a fuzzy match
        },
    },