Skip to content

CodeCoupler Webpack Externals Plugin Setup

Install package:

1
npm i @codecoupler/cc-webpack-externals-plugin -D
  • You must be running Node 10.0 along with Webpack 5.0 or higher for version 2.x of this plugin.
  • You must be running Node 8.6 or higher for version 1.x of this plugin

Add to your Webpack configuration:

1
2
3
4
const ccWebpackExternalsPlugin = require("@codecoupler/cc-webpack-externals-plugin");
module.exports = {
  plugins: [new ccWebpackExternalsPlugin(options)],
};

Options

The options argument is optional and can be an object. You can specify the following options:

  • packagesPath: (string; default: "vendor") The subfolder name where to copy all the assets.
  • useCdn: (boolean; default: false) If true no assets will be copied and CDN links will be injected instead.
  • getCdnPath: (function(name, version, path): string; default: (name, version, path) => //cdn.jsdelivr.net/npm/${name}@${version}/${path}) This function should return a string to inject as CDN link to the assets.
  • versionsVariable: (string; default: "window.ccExternals") This variable will be injected automatically in your bundle. Here you can read the paths of each externalized module. This is important if you need to access assets of the module dynamically. Read below more details.
  • includeCcExternals: 1 (boolean; default: false) Enable including externals configurations from packages of scope @cc-external

The following option should be used only for debuging the library:

  • projectRootFolder: Simulate another project path where @cc-external packages will be searched. By default the packages will be searched in <Current Directory>/node_modules/@cc-external.
  • debugOutput: If true the final configurations will be printed into the console.
  • debugOutputRaw: If set to true no ANSI escape codes for colorizing will be used in the debug output.

Switching to CDN

If you do not want to copy any files to your destination folder you can switch to CDN with just one option:

1
2
3
new ccWebpackExternalsPlugin({
  useCdn: true,
});

This will replace the urls in the script and the link tags with CDN targets, pointing to the exact version of the locally installed package. Here an example of using jQuery from CDN:

1
<script src="//cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js">

You can of course specify your own conversion function. Here is an example how to use unpkg instead of jsdelivr:

1
2
3
4
new ccWebpackExternalsPlugin({
  useCdn: true,
  getCdnPath: (name, version, path) => "//unpkg.com/${name}@${version}/${path}",
});

  1. In version 2 and below this feature was enabled by default and could not be disabled.