Peer Dependencies

In notebook:
FrontEndMasters Creating an Open Source JavaScript Library on Github
Created at:
2017-07-18
Updated:
2017-07-18
Tags:
Webpack libraries React JavaScript

###Questions

Question: there was a unique random array dependency. Is it injected directly in the code?

Yes. But. When we send it to the registry, we don't include directly dependencies in the code. It is only included when in the browser targeted (UMD) version.

This can create some redundancy when you use multiple libararies that depend on the same modules in the browser. Gzip will take care of this. But. If you use Angular or React in your library, you don't want to bundle all this in your dist code.

##Including big libraries in your code with peerDependencies

You can have a problem when your library includes one version of React, but the user depends on another version of it. You can have the "peerDependencies": {...}. This tells npm to use the user installed version of this dependency. If they don't have it installed, then it gives them a warning, or fail on npm 2.0 and above.

###Now, manage the peerDependencies with Webpack

need to edit .webpack.config.babel.js:

  ..
export default {
  context,
  entry: './index',
  output: {
    path: join(__dirname, 'dist'),
    libraryTarget: 'umd',
    library: 'starWarsNames',
  },
  devtool: 'source-map',
  // **** 1.	Add the externals
  // that you don't want to include
  externals: [
    'unique-random-array'
    ]
  module: {
    loaders: [
      {test: /\.js$/, loaders: ['babel'], include: context},
      {test: /\.json$/, loaders: ['json'], include: context},
    ],
  },
  ..

Now, we excluded 'unique-random-array' from Webpack. It will reference this module as a passed argument to its IFEE but will not include the actual code.

With the externals API you can configure how to call your excluded module. This is recommended for all the big frameworks and libraries.

Question: can you manage versions with it?

With the UMD you cannot specify which version you need. You need to document it. You have to do something at runtime to tell that it's not compatible (Angular 2 vs Angular 1 for example). But he doesn't know a standard solution that could do this.

When you use peerDependencies make sure you give a loose version range so that people don't get unnecessary warnings:

 "peerDependencies":
  "unique-random-array": "^1.0.0 || ^2.0.0-beta"

Or you can just add * to say that it works with any version.

Question: Are there any other alternative to Webpack?

He really likes Webpack, for him it's easy to install and configure. Browserify is becoming less popular.

##Rollup

If you really want to minimise the bundle size then Rollup is a great alternative. Instead of adding its own require system, it bundles the entire code into one function (IFEE option). You have one file that holds everything inside one function.