6

I am just starting to use webpack 3 and dllplugin. I managed to find a few blog articles abt. this. However none of them with a proper code sample/ GitHub samplecode. Does anyone know any references to sample code for this/ working example?

bier hier
  • 20,970
  • 42
  • 97
  • 166

1 Answers1

5

This is a good simple example:

We define our functions in vendor.js (this is the library that we are going to reference as DLL).

vendor.js

function square(n) {
  return n*n;
}

module.exports = square;

Then define WebPack configuration to export this as a DLL using DllPlugin.

vendor.webpack.config.js

var webpack = require('webpack');
module.exports = {
  entry: {
    vendor: ['./vendor'],
  },
  output: {
    filename: 'vendor.bundle.js',
    path: 'build/',
    library: 'vendor_lib',
  },
  plugins: [new webpack.DllPlugin({
    name: 'vendor_lib',
    path: 'build/vendor-manifest.json',
  })]
};

In our application, we simply reference the created DLL using require(./dllname)

app.js

var square = require('./vendor');
console.log(square(7));

And in WebPack build configuration, we use DllReferencePlugin to reference the created DLL.

app.webpack.config.js

var webpack = require('webpack');
module.exports = {
  entry: {
    app: ['./app'],
  },
  output: {
    filename: 'app.bundle.js',
    path: 'build/',
  },
  plugins: [new webpack.DllReferencePlugin({
    context: '.',
    manifest: require('./build/vendor-manifest.json'),
  })]
};

Finally, we need to compile the DLL, and then the application using WebPack.

Compile with:

webpack --config vendor.webpack.config.js
webpack --config app.webpack.config.js

To include the file inside HTML, use simple JS include script tag.

Use with the following index.html

<script src="build/vendor.bundle.js"></script>
<script src="build/app.bundle.js"></script>

Reference: https://gist.github.com/robertknight/058a194f45e77ff95fcd Also you can find more DLL examples in WebPack repository: https://github.com/webpack/webpack/tree/master/examples

mohghaderi
  • 2,520
  • 1
  • 19
  • 12
  • In your app.js, why you `require('./vendor')`? Shouldn't you `require('./vendor.bundle.js')`? – PunCha Jan 22 '19 at 00:42
  • 1
    @PunCha you need to reference source files in your source code (.js). bundle file is the output and will be generated by the tool – mohghaderi Jan 22 '19 at 13:11
  • what's the meaning of `vendor_lib` in `vendor.webpack.config.js`?they don't appear in `app.webpack.config.js` and `app.js` and `index.html` – tcpiper Jul 23 '20 at 09:05
  • @tcpiper vendor_lib here is the name of the library. app.js uses require to include vendor.js – mohghaderi Aug 27 '20 at 21:15