Coder Social home page Coder Social logo

mmiller42 / html-webpack-externals-plugin Goto Github PK

View Code? Open in Web Editor NEW
99.0 6.0 16.0 503 KB

Webpack plugin that works alongside html-webpack-plugin to use pre-packaged vendor bundles.

License: MIT License

JavaScript 100.00%
webpack webpack-plugin html-webpack-plugin externals

html-webpack-externals-plugin's Introduction

html-webpack-externals-plugin CircleCI

🚨 DEPRECATED 🚨

Sorry, this module is no longer maintained, and its functionality is baked into wonderful plugins by jharris4, html-webpack-tags-plugin and html-webpack-deploy-plugin.

You're likely to run into issues with it and it has not been used with recent Webpack projects.


Webpack plugin that works alongside html-webpack-plugin to use pre-packaged vendor bundles.

How it works

This plugin is very simple and just encapsulates two other Webpack plugins to do the heavy lifting. It:

  1. modifies your Webpack config at runtime to add your vendor modules to the externals property.
  2. runs the copy-webpack-plugin to copy your vendor module assets into the output path.
  3. runs the html-webpack-include-assets-plugin to add your vendor module bundles to the HTML output.

Installation

npm install --save-dev html-webpack-externals-plugin

Usage

Require the plugin in your Webpack config file.

const HtmlWebpackExternalsPlugin = require('html-webpack-externals-plugin')

Then instantiate it in the plugins array, after your instance of html-webpack-plugin.

plugins: [
  new HtmlWebpackPlugin(),
  new HtmlWebpackExternalsPlugin(
    // See API section
  ),
]

API

The constructor takes a configuration object with the following properties.

Property Type Description Default
externals array<object> An array of vendor modules that will be excluded from your Webpack bundle and added as script or link tags in your HTML output. None
externals[].module string The name of the vendor module. This should match the package name, e.g. if you are writing import React from 'react', this would be react. None
externals[].entry string | array<string> | object | array<object | string> The path, relative to the vendor module directory, to its pre-bundled distro file. e.g. for React, use dist/react.js, since the file exists at node_modules/react/dist/react.js. Specify an array if there are multiple CSS/JS files to inject. To use a CDN instead, simply use a fully qualified URL beginning with http://, https://, or //.

For entries whose type (JS or CSS) cannot be inferred by file extension, pass an object such as { path: 'https://some/url', type: 'css' } (or type: 'js').
None
externals[].entry.path string If entry is an object, the path to the asset. None
externals[].entry.type 'js'|'css' The asset type, if it cannot be inferred. Inferred by extension when possible
externals[].entry
  .cwpPatternConfig
object The properties to set on the copy-webpack-plugin pattern object. This object is merged in with the default from and to properties which are generated by the externals plugin. {}
externals[].entry
  .attributes
object.<string,string> Additional attributes to add to the injected tag. {}
externals[].global string | null For JavaScript modules, this is the name of the object globally exported by the vendor's dist file. e.g. for React, use React, since react.js creates a window.React global. For modules without an export (such as CSS), omit this property or use null. null
externals[].supplements array<string> | array<object> For modules that require additional resources, specify globs of files to copy over to the output. e.g. for Bootstrap CSS, use ['dist/fonts/'], since Glyphicon fonts are referenced in the CSS and exist at node_modules/bootstrap/dist/fonts/. Supplements can be specified as just an array of paths, or an array of objects with a path and copy plugin pattern object. []
externals[].supplements[]
  .path
string The glob path to copy assets from. None
externals[].supplements[]
  .cwpPatternConfig
object The properties to set on the copy-webpack-plugin pattern object. This object is merged in with the default from and to properties which are generated by the externals plugin. {}
externals[].append boolean Set to true to inject this module after your Webpack bundles. false
hash boolean Set to true to append the injected module distro paths with a unique hash for cache-busting. false
outputPath string The path (relative to your Webpack outputPath) to store externals copied over by this plugin. vendor
publicPath string | null Override Webpack config's publicPath for the externals files, or null to use the default output.publicPath value. null
files string | array<string> | null If you have multiple instances of HtmlWebpackPlugin, use this to specify globs of which files you want to inject assets into. Will add assets to all files by default. null
cwpOptions object The options object to pass as the copy-webpack-plugin constructor's second parameter. {}
enabled boolean Set to false to disable the plugin (useful for disabling in development mode). true

Examples

Local JS external example

This example assumes jquery is installed in the app. It:

  1. adds jquery to your Webpack config's externals object to exclude it from your bundle, telling it to expect a global object called jQuery (on the window object)
  2. copies node_modules/jquery/dist/jquery.min.js to <output path>/vendor/jquery/dist/jquery.min.js
  3. adds <script type="text/javascript" src="<public path>/vendor/jquery/dist/jquery.min.js"></script> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'jquery',
      entry: 'dist/jquery.min.js',
      global: 'jQuery',
    },
  ],
})

Local CSS external example

This example assumes bootstrap is installed in the app. It:

  1. copies node_modules/bootstrap/dist/css/bootstrap.min.css to <output path>/vendor/bootstrap/dist/css/bootstrap.min.css
  2. adds <link href="<public path>/vendor/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'bootstrap',
      entry: 'dist/css/bootstrap.min.css',
    },
  ],
})

Local external with supplemental assets example

This example assumes bootstrap is installed in the app. It:

  1. copies node_modules/bootstrap/dist/css/bootstrap.min.css to <output path>/vendor/bootstrap/dist/css/bootstrap.min.css
  2. copies all contents of node_modules/bootstrap/dist/fonts/ to <output path>/vendor/bootstrap/dist/fonts/
  3. adds <link href="<public path>/vendor/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'bootstrap',
      entry: 'dist/css/bootstrap.min.css',
      supplements: ['dist/fonts/'],
    },
  ],
})

CDN example

This example does not require the jquery module to be installed. It:

  1. adds jquery to your Webpack config's externals object to exclude it from your bundle, telling it to expect a global object called jQuery (on the window object)
  2. adds <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/jquery.min.js"></script> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'jquery',
      entry: 'https://unpkg.com/[email protected]/dist/jquery.min.js',
      global: 'jQuery',
    },
  ],
})

URL without implicit extension example

Some CDN URLs don't have file extensions, so the plugin cannot determine whether to use a link tag or a script tag. In these situations, you can pass an object in place of the entry property that specifies the path and type explicitly.

This example uses the Google Fonts API to load the Roboto font. It:

  1. adds <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'google-roboto',
      entry: {
        path: 'https://fonts.googleapis.com/css?family=Roboto',
        type: 'css',
      },
    },
  ],
})

Module with multiple entry points example

Some modules require more than one distro file to be loaded. For example, Bootstrap has a normal and a theme CSS entry point.

This example assumes bootstrap is installed in the app. It:

  1. copies node_modules/bootstrap/dist/css/bootstrap.min.css to <output path>/vendor/bootstrap/dist/css/bootstrap.min.css
  2. copies node_modules/bootstrap/dist/css/bootstrap-theme.min.css to <output path>/vendor/bootstrap/dist/css/bootstrap-theme.min.css
  3. copies all contents of node_modules/bootstrap/dist/fonts/ to <output path>/vendor/bootstrap/dist/fonts/
  4. adds <link href="<public path>/vendor/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> to your HTML file, before your chunks
  5. adds <link href="<public path>/vendor/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet"> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'bootstrap',
      entry: ['dist/css/bootstrap.min.css', 'dist/css/bootstrap-theme.min.css'],
      supplements: ['dist/fonts/'],
    },
  ],
})

Appended assets example

Sometimes you want to load the external after your Webpack chunks instead of before.

This example assumes bootstrap is installed in the app. It:

  1. copies node_modules/bootstrap/dist/css/bootstrap.min.css to <output path>/vendor/bootstrap/dist/css/bootstrap.min.css
  2. adds <link href="<public path>/vendor/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> to your HTML file, after your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'bootstrap',
      entry: 'dist/css/bootstrap.min.css',
      append: true,
    },
  ],
})

Cache-busting with hashes example

You can configure the plugin to append hashes to the query string on the HTML tags so that, when upgrading modules, a new hash is computed, busting your app users' caches. Do not use this in tandem with CDNs, only when using local externals.

This example assumes bootstrap is installed in the app. It:

  1. copies node_modules/bootstrap/dist/css/bootstrap.min.css to <output path>/vendor/bootstrap/dist/css/bootstrap.min.css
  2. adds <link href="<public path>/vendor/bootstrap/dist/css/bootstrap.min.css?<unique hash>" rel="stylesheet"> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'bootstrap',
      entry: 'dist/css/bootstrap.min.css',
    },
  ],
  hash: true,
})

Customizing output path example

By default, local externals are copied into the Webpack output directory, into a subdirectory called vendor. This is configurable.

Do not include a trailing slash or leading slash in your output path, they are concatenated automatically by the plugin.

This example assumes bootstrap is installed in the app. It:

  1. copies node_modules/bootstrap/dist/css/bootstrap.min.css to <output path>/thirdparty/bootstrap/dist/css/bootstrap.min.css
  2. adds <link href="<public path>/thirdparty/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'bootstrap',
      entry: 'dist/css/bootstrap.min.css',
    },
  ],
  outputPath: 'thirdparty',
})

Customizing public path example

By default, local externals are resolved from the same root path as your Webpack configuration file's output.publicPath, concatenated with the outputPath variable. This is configurable.

You should include a trailing slash in your public path, and a leading slash if you want it to resolve assets from the domain root.

This example assumes bootstrap is installed in the app. It:

  1. copies node_modules/bootstrap/dist/css/bootstrap.min.css to <output path>/vendor/bootstrap/dist/css/bootstrap.min.css
  2. adds <link href="/assets/vendor/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'bootstrap',
      entry: 'dist/css/bootstrap.min.css',
    },
  ],
  publicPath: '/assets/',
})

Adding custom attributes to tags example

Sometimes you may want to add custom attributes to the link or script tags that are injected.

This example does not require the jquery module to be installed. It:

  1. adds jquery to your Webpack config's externals object to exclude it from your bundle, telling it to expect a global object called jQuery (on the window object)
  2. adds <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'jquery',
      entry: {
        path: 'https://code.jquery.com/jquery-3.2.1.js',
        attributes: {
          integrity: 'sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=',
          crossorigin: 'anonymous',
        },
      },
      global: 'jQuery',
    },
  ],
})

Passing an options argument to the copy-webpack-plugin constructor example

You can change the default context for all patterns that are copied by the copy-webpack-plugin, enable debug mode, etc. by passing additional options to the plugin.

This example assumes bootstrap is installed in the app via bower. It:

  1. copies bower_components/bootstrap/dist/css/bootstrap.min.css to <output path>/vendor/bootstrap/dist/css/bootstrap.min.css
  2. adds <link href="<public path>/vendor/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'bootstrap',
      entry: 'dist/css/bootstrap.min.css',
    },
  ],
  cwpOptions: {
    context: path.resolve(__dirname, 'bower_components'),
  },
})

Passing custom options to copy-webpack-plugin for an entry example

In certain instances, you might want to control the properties that are passed in with the pattern object provided to copy-webpack-plugin, in order to control context, caching, output path, etc.

This example assumes bootstrap is installed in the app via bower. It:

  1. copies bower_components/bootstrap/dist/css/bootstrap.min.css to <output path>/vendor/bootstrap/dist/css/bootstrap.min.css
  2. adds <link href="/assets/vendor/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'bootstrap',
      entry: {
        path: 'dist/css/bootstrap.min.css',
        cwpPatternConfig: {
          context: path.resolve(__dirname, 'bower_components'),
        },
      },
    },
  ],
})

Passing custom options to copy-webpack-plugin for a supplement example

In certain instances, you might want to control the properties that are passed in with the pattern object provided to copy-webpack-plugin, in order to control context, caching, output path, etc.

This example assumes ./mod is a directory in your app that contains some dist files.

  1. copies mod/dist/mod.css to <output path>/vendor/mod/dist/mod.css
  2. copies all contents of mod/dist/{a,b}/ to <output path>/vendor/mod/dist/{a,b}/, passing nobrace to node-glob so that {a,b} is matched literally instead of expanded into a glob
  3. adds <link href="<public path>/vendor/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> to your HTML file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'mod',
      entry: 'dist/mod.css',
      supplements: [
        {
          path: 'dist/{a,b}/',
          cwpPatternConfig: {
            fromArgs: {
              nobrace: true,
            },
          },
        },
      ],
    },
  ],
  cwpOptions: {
    context: __dirname,
  },
})

Specifying which HTML files to affect example

If you are using multiple instances of html-webpack-plugin, by default the assets will be injected into every file. This is configurable.

This example assumes bootstrap is installed in the app. It:

  1. copies node_modules/bootstrap/dist/css/bootstrap.min.css to <output path>/vendor/bootstrap/dist/css/bootstrap.min.css
  2. adds <link href="/public/vendor/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> to only the about.html file, before your chunks
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'bootstrap',
      entry: 'dist/css/bootstrap.min.css',
    },
  ],
  files: ['about.html'],
})

Disabling the plugin

Sometimes you only want the plugin to be activated in certain environments. Rather than create separate Webpack configs or mess with splicing the plugins array, simply set the enabled option to false to disable the externals plugin entirely.

new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'jquery',
      entry: 'dist/jquery.min.js',
      global: 'jQuery',
    },
  ],
  enabled: process.env.NODE_ENV === 'production',
})

html-webpack-externals-plugin's People

Contributors

greenkeeper[bot] avatar mmiller42 avatar norangit avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

html-webpack-externals-plugin's Issues

missing directory lib in npm package

version 3.3.1

missing lib directory after install, so require('html-webpack-externals-plugin') will fail.

reproduce:

$ npm install html-webpack-externals-plugin
$ ls node_modules/html-webpack-externals-plugin
LICENSE  README.md  package.json  src

Accurate path?

Why can't we achieve the precise path through the way of outputPath:'static/js/[name].js'?

example:

new HtmlWebpackExternalsPlugin({
externals: [{
module: 'jquery',
entry: 'jquery/dist/jquery.min.js',
global: 'jQuery',
}, ],
outputPath: 'static/js/[name].js'
}))

insert:

<script type="text/javascript" src="static/js/jquery.min.js"></script>

Use Node module resolution algorithm

Currently paths are manually resolved relative to the node_modules directory in the project root. This doesn’t work when the module is installed in the parent directory, which might be the case in instances such as Yarn’s workspace configuration for monorepos. Infer the module’s location instead via the resolution algorithm which traverses up the directory tree.

/ (slash) at the beginning?

Hi

Using the configuration mentioned here https://www.npmjs.com/package/html-webpack-externals-plugin#example , I'm getting an extra slash at the beginning of the of the or <script> tag.
.e.g - <link href="https://_SOME_URL" >
becomes
<link href="/https://_SOME_URL" >

with an extra slash before the https.. any idea or thoughts?


found the issue.. it was because of the publicPath of config.output.. is there anyway for this configuration to now affect the html-webpack-externals-plugin ?

How to reference a node_module in the compiled bundle

In my electron project, I've an internal node_modules folder whose all dependencies have been under externals in webpack and they are directly reference by var dep = require('dep'). When the webpack script is run in prod mode, a physical built file is generate that can easily reference the dependencies from any available node_modules.

But in webpack dev mode, I'm using html-webpack-plugin, which creates html file in memory and it never references those externals.

I want to specify that node_modules to this plugin so that all un-resolved dependencies can be looked into this folder as well.

Consider updating to html-webpack-tags-plugin

Hi @mmiller42,

Just thought I'd write a quick message to let you know that html-webpack-include-assets-plugin plugin has been renamed to html-webpack-tags-plugin.

Also, a bunch of new features were added, including built-in support for externals which may be of interest since you have a similar feature in this plugin.

There's also the html-webpack-deploy-plugin plugin built on top of it that provides some nice features for deploying/including assets from node_modules packages.

Obviously feel free to ignore these plugins/changes, but I'd be happy to help if you have any questions about upgrading.

Cheers!

when multiple html files are import external automatically according to the import situation

Usually an application will have a lot of pages, so it is not possible to use files specify a page will append which external resource. if have a way to import externals automatically according import situcation in src files.

for example, one file (admin.html) need react,moment, another only need react(help.html). i configed all externals in plugin options. in build file, admin.html have react,moment scripts and help.html only react script.

this is me how to config webpack entry and html-webpack-plugin:

var pages = glob.sync('*.page.js', {cwd: cwd + '/src/pages', matchBase: true});
var entry = {};
var htmls = [];
pages.forEach((item) => {
    let chunk = 'pages/' + item.slice(0, 0 - '.page.js'.length);
    entry[chunk] = ['./src/pages/' + item];
    htmls.push(new HtmlWebpackPlugin({
        filename: path.resolve('./build') + '/' + item.slice(0, 0 - '.page.js'.length) + '.html',
        template: path.resolve(cwd, 'src/htmls/index.html'),
        chunks: [chunk],
        hash: true
    }))
});
//... more code

Unmet dependency warning on installed package.

npm WARN [email protected] requires a peer of html-webpack-plugin@^2.0.0 but none was installed.
is shown as an error everytime i run a command on npm. but then I do have an html-webpack-plugin package installed in my project.

my dependencies being:

"devDependencies": {
    "autoprefixer": "^8.6.3",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "bootstrap": "^4.1.1",
    "css-loader": "^0.28.11",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "html-webpack-externals-plugin": "^3.8.0",
    "html-webpack-plugin": "^3.2.0",
    "jquery": "^3.3.1",
    "node-sass": "^4.9.0",
    "optimize-css-assets-webpack-plugin": "^4.0.2",
    "popper": "^1.0.1",
    "postcss-loader": "^2.1.5",
    "sass-loader": "^7.0.3",
    "style-loader": "^0.21.0",
    "uglifyjs-webpack-plugin": "^1.2.6",
    "webpack": "^4.12.1",
    "webpack-cli": "^3.0.8",
    "webpack-dev-server": "^3.1.4",
    "webpack-merge": "^4.1.3"
  },
  "dependencies": {
    "@material/top-app-bar": "^0.36.1",
    "classnames": "^2.2.6",
    "gentelella": "^1.4.0",
    "history": "^4.7.2",
    "prop-types": "^15.6.2",
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-router": "^4.3.1"
  }

Altering css-files array while accessing it changes accessed indexes

Line 150 (current version):

//make sure that the order of lib css before the css of module for( i = 0, len = extractedCss.length; i < len; i++ ){ extractedCss[i] = Object.assign({}, pluginArgs.head.splice(extractedCss[i], 1)[0]); // <<< this Line } pluginArgs.head = extractedCss.concat( pluginArgs.head ); callback();

This will alter the indexes of the pluginArgs.head array while you try to access the indexes in that order which results in accessing the wrong and also empty indexes. This caused my html to have an empty tag and the last two css files have been added to the body instead of the head-section.

Inject external file many times

I have many entries and each entry need to inject an external javascript called aepmod.js (just like a CDN jquery), but I got wrong times of injection in my dist folder.
image
image

The first file gets one inject.
The second one gets two,
The third one gets three
.....
The last one gets many times (The times depend on the order of my file)!
image
Following is my webpack production config:
image
And the path in 'externals' config represents the URL of aepmod.js

Support SRI

I'm injecting CDN URLs with this plugin and want to add subresource integrity attribute to scripts as well.

Chrome reported some library "is not defined" when using CDN

Hi I want to use CDN for my production build. Although I can load jQuery (as your example shows), some library was reported "not define", e.g. I want to load ztree use CDN and I use like this

    new HtmlWebpackExternalsPlugin({
      externals: [
        {
          module: 'ztree',
          entry: 'https://cdn.bootcss.com/zTree.v3/3.5.24/js/jquery.ztree.all.min.js',
          global: 'ztree'
        },
      ],
    }),

In my vue code import zTree from 'ztree'

When I opened my page, Chrome reported: So what did I do wrong here ?

bootstrap cff876d6b8365dfe7db2:146 ReferenceError: ztree is not defined
at Object.jbSp (external "ztree":1)
at t (bootstrap cff876d6b8365dfe7db2:54)
at Object.8Yog (tree.js:1602)
at t (bootstrap cff876d6b8365dfe7db2:54)
at Object.PhPB (noQuestion_bg.png:1)
at t (bootstrap cff876d6b8365dfe7db2:54)

The external ztree only has codes

module.exports = ztree;

//////////////////
// WEBPACK FOOTER
// external "ztree"
// module id = jbSp
// module chunks = 25

Cache busting assets via [hash] or [chunkhash] rather than query parameter

As I understand, using a query parameter to cachebust assets (e.g. bootstrap.min.css?1337) is the Webpack 1 way. Webpack 2 switched to renaming assets files to include a hash via variable [hash] or [chunkhash] (e.g. 'boostrap.min.[chunkhash].css' becomes boostrap.min.1337.css).

Could you update this plugin to support the use of [hash] and [chunkhash] in the 'entry' field under 'externals'?

NPM audit fails with moderate vulnerability

Hey,
npm audit currently shows a moderate vulnerability for your package html-webpack-externals-plugin, because of a vulnerability in the serialize-javascript package within the copy-webpack-plugin package. Maybe you should consider updating either the copy-webpack-plugin package or the serialize-javascript package to resolve this.

npm audit output:

Moderate Cross-Site Scripting
Package serialize-javascript
Patched in >=2.1.1
Dependency of html-webpack-externals-plugin
Path html-webpack-externals-plugin > copy-webpack-plugin >
serialize-javascript
More info https://npmjs.com/advisories/1426

Assets insert position

I used latest version of your plugin, I find the externals are inserted before chunks assets. Can you implement an option to specific insert position?

attributes passed to wrong tag

if I include a favicon in the HtmlWebpackPlugin options the attributes are passed to the favicon instead to the external module in which I originally defined them in

unable to resolve the external "path" of an existing file...

Hello,

When I try to compilate, I meet the following error :

"Unable to resolve the external path /server/app/src/deps/file.js"

Whereas the file does exist in this folder.

here is the part of the configuration :

new HtmlWebpackPlugin({ template: './src/public/index.html', chunksSortMode: 'dependency', lib: ['sockjs-client', 'sockjs-event'] })

new HtmlWebpackExternalsPlugin([ { name: 'sockjs-client', var: 'sockjs-client', path: __dirname + '/deps/sockjs-client.js' }, { name: 'sockjs-event', var: 'sockjs-event', path: __dirname + '/deps/sockjs-event.js' } ])

Anyone has a clue of the reason why it doesn't work properly ?

(configuration : node v6.9.4 + npm 4.6 + webpack 2.6)

Support cross-origin attribute to CDN URLs

I'm using this plugin to specify that React will be loaded from a CDN, like so:

new HtmlWebpackExternalsPlugin({
  externals: [
    {
      module: 'react',
      entry: 'https://unpkg.com/[email protected]/dist/react.min.js',
      global: 'React'
    },
    {
      module: 'react-dom',
      entry: 'https://unpkg.com/[email protected]/dist/react-dom.min.js',
      global: 'ReactDOM'
    }
  ]
}),

It would be nice if I could specify a new option, like "crossOrigin": true that could add the attribute "cross-origin" to the script tag.

To understand how that is important:
https://twitter.com/dan_abramov/status/893099358484353024

I tried to use this plugin: https://github.com/dentuzhik/html-webpack-crossorigin-plugin
But it adds the attribute to all the <script> tags and I think that's not ideal.

externals copied more times

a part of config below:
HtmlWebpackPlugin {
options:
{ template: '/xxxxx/first/index.html',
filename: 'first.html',
.....
} },
HtmlWebpackPlugin {
options:
{ template: '/xxxxx/second/index.html',
filename: 'second.html',
.....
} },
HtmlWebpackExternalsPlugin {
externals: [
{
module: (function(){console.log('react'); return 'react'}()),
entry: 'https://11.url.cn/now/lib/16.2.0/react.min.js',
global: 'React',
}]
}

The output file:
firest.html

<title>First</title>
<script type="text/javascript" src="https://11.url.cn/now/lib/16.2.0/react.min.js"></script></script><script type="text/javascript" src="first_e369253c.js"></script>

second.html

<title>Second</title>
<script type="text/javascript" src="https://11.url.cn/now/lib/16.2.0/react.min.js"></script><script type="text/javascript" src="https://11.url.cn/now/lib/16.2.0/react.min.js"></script><script type="text/javascript" src="second_adf7c207.js"></script>

The second.html repeat call HtmlWebpackExternalsPlugin.
if I have the third.html config ,the external file will appear three times in third.html.
I've on idea how to get the right file.

ReactDom is not defined

hello everyone, i have a question that i imort react and set externals, but also has error
import React from 'react'
import ReactDom from 'react-dom'

new HtmlWebpackExternalsPlugin({
externals: [{
module: 'react',
entry: 'https://11.url.cn/now/lib/16.2.0/react.min.js',
global: 'React',
},
{
module: 'react-dom',
entry: 'https://11.url.cn/now/lib/16.2.0/react-dom.min.js',
global: 'ReactDom',
}],
})

but also console error

external "ReactDom":1 Uncaught ReferenceError: ReactDom is not defined
at Object. (external "ReactDom":1)
at n (bootstrap:19)
at Module. (index.js:89)
at n (bootstrap:19)
at bootstrap:83
at bootstrap:83

bootstrap.js must need global?

code:

new HtmlWebpackExternalsPlugin({
        externals: [
          {
          //   module: 'jquery',
          //   entry: '//unpkg.com/[email protected]/dist/jquery.min.js',
          //   global: '$',
          // }, {
            module: 'bootstrap.min.js',
            entry: {path: '//cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js', type: 'js'},
          }, {
            module: 'bootstrap.min.css',
            entry: {path: '//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css', type: 'css'},
          // }, {
          //   module: 'react',
          //   entry: {path: '//cdn.bootcss.com/react/0.14.8/react.min.js', type: 'js'},
          //   global: 'React'
          // }, {
          //   module: 'react-dom',
          //   entry: {path: '//cdn.bootcss.com/react/0.14.8/react-dom.min.js', type: 'js'},
          //   global: 'ReactDOM'
          }
        ],
        files: ['../../../view/front/test_index.html', '../../../view/front/test_detail.html'],
      })

error:
ERROR in chunk test_index_renderer [entry]
js/[name].bundle.js
Cannot read property 'var' of null
Child html-webpack-plugin for "../../../view/front/test_index.html":
+ 3 hidden modules
Child html-webpack-plugin for "../../../view/front/test_detail.html":
+ 3 hidden modules

question:
option.externals[].global: For modules without an export (such as CSS), omit this property or use null, js such as bootstrap.min.js alse need global?

How to use with Typescript?

Hi,

I'm trying to incorporate this into my production build. I am externalizing React and React-DOM from my local node_modules. When I go to see index.html in the browser, I get require() is not defined, React is not defined, etc.

AFAI understand, externalizing these libs means that in my code, I don't have to import them, since the libraries will be included in <script> tags in my index.html. Now, I want to be able to develop as usual. In my React files, I am importing React, ReactDom, and tons of other things. When I go to build, TypeScript says that I need to import, or Webpack won't go through with the build. I tried setting module: none in my tsconfig, but that means I won't be able to import anything ever.

How can I get this to work?

webpack.config.prod.js

const path = require('path');
const nodeExternals = require('webpack-node-externals');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackExternalsPlugin = require('html-webpack-externals-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');

const externals = [
  {
    module: 'react',
    entry: 'cjs/react.production.min.js',
    global: 'React',
  },
  {
    module: 'react-dom',
    entry: 'cjs/react-dom.production.min.js',
    global: 'ReactDOM',
  },
];

module.exports = [
  {
    mode: 'production',
    entry: path.resolve(__dirname, 'src/app.ts'),
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist'),
    },
    module: {
      rules: [
        {
          test: /\.ts?$/,
          loader: 'ts-loader',
          exclude: /node_modules/,
          options: {
            configFile: path.resolve(__dirname, 'tsconfig.json'),
          },
        },
      ],
    },
    resolve: {
      extensions: ['.ts', '.js'],
    },
    target: 'node',
    externals: [nodeExternals()],
  },
  {
    mode: 'production',
    entry: path.resolve(__dirname, 'src/client/index.tsx'),
    output: {
      filename: '[name].[contentHash].bundle.js',
      path: path.resolve(__dirname, 'dist/public'),
    },
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          loader: 'ts-loader',
          exclude: /node_modules/,
          options: {
            configFile: path.resolve(__dirname, 'src/client/tsconfig.json'),
          },
        },
        {
          test: /\.css$/,
          use: ['css-loader'],
        },
      ],
    },
    resolve: {
      extensions: ['.tsx', '.ts', '.js', '.css'],
    },
    target: 'web',
    optimization: {
      minimizer: [new OptimizeCssAssetsPlugin(), new TerserPlugin()],
    },
    plugins: [
      new MiniCssExtractPlugin({ filename: '[name].[contentHash].css' }),
      new CleanWebpackPlugin(),
      new HtmlWebpackPlugin({
        template: path.resolve(__dirname, 'src/client/public/index.html'),
        // minify: {
        //   removeAttributeQuotes: true,
        //   collapseWhitespace: true,
        //   removeComments: true,
        // },
      }),
      new HtmlWebpackExternalsPlugin({ externals, hash: true }),
    ],
  },
];

Usage for files outside node_modules?

Hi, is there a way to make this plug-in work for my own files, that are not in node_modules?

For example:
I have some configuration data files in app/js/config/
I want these files to be excluded from all bundles, copied to the output (dist) folder and read from there at runtime, which is exactly what this plug-in does, but for files in node_modules.

I managed to get it to copy a test file and insert the script tag in index.html, but the contents of the test.js file is still bundled and read from there. Here's my experimental config:

new HtmlWebpackExternalsPlugin({
externals: [
{
module: 'test',
entry: '../../js/config/test.js',
global: 'test',
},
],
})

Any help will be greatly appreciated!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.