how to force webpack to load umd bundle of a library

2.3k views Asked by At

I'm writing an angular1 + angular2 hybrid application which uses webpack as package bundler.

In my code I import a library (@angular/upgrade) in this way

import { UpgradeModule } from '@angular/upgrade/static';

Angular upgrade library is sitting in node_module folder with the following tree structure (simplified):

@angular/upgrade
├── bundles
│   ├── upgrade-static.umd.js
│   ├── upgrade-static.umd.min.js
│   ├── upgrade.umd.js
│   └── upgrade.umd.min.js
├── index.d.ts
├── index.js
├── index.js.map
├── index.metadata.json
├── package.json
├── static
│   └── package.json
├── static.d.ts
├── static.js.map
├── static.metadata.json
└── static.js

The problem is that by default webpack resolve my import statement loading @angular/upgrade/static.js, an ES6 file which, once bundled with the rest of the code generate errors.

What I'd like webpack to do instead is loading @angular/upgrade/static/package.json which contains the right main definition pointing to the umd bundle

{"main": "../bundles/upgrade-static.umd.js"}

Is that achievable?

Thanks, Gab

2

There are 2 answers

0
gabric On BEST ANSWER

Although the module resolution described here: https://webpack.github.io/docs/resolving.html should be able to do what I've described above by default, in order to achieve that I had to use the resolve.alias property. Here's the configuration that I've used:

resolve: {
        extensions: [ '.js', '.ts', '' ],
        modulesDirectories: [ path.resolve( __dirname, 'node_modules' ) ],
        alias: {
            '@angular/upgrade/static$': '../../node_modules/@angular/upgrade/bundles/upgrade-static.umd.js'
        }
    },
1
Drew Schuster On

Does import UpgradeModule from '@angular/upgrade/bundles/upgrade-static.umd.js'; work?

Webpack only follows the main in package.json if package.json is at the root level of the npm module, so in this case you'll have to access the file you want directly.