Code Monkey home page Code Monkey logo

dynamic-cdn-webpack-plugin's People

Contributors

aulisius avatar davidjb avatar mastilver avatar nreilingh 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

dynamic-cdn-webpack-plugin's Issues

Babel Example

Hey! Great work, saw this at a talk today from https://twitter.com/swyx at ReactNYC meetup.

Can we add Babel / ES6 syntax for installation:

import DynamicCdnWebpackPlugin from 'dynamic-cdn-webpack-plugin'

  plugins: [
     ...,
    new DynamicCdnWebpackPlugin()
  ]

I'm having my server run fine, but it is not building with expected values

Feat: take array of resolvers

ideally each resolver should target a specific domain name (so there is no need to make multiple connection handshakes)

So we should allow multiple revolvers to be passed in so if the first one can't find the module, the request is being passed down to the next

It will also make it easier for #23

incompatibility with html-webpack-inline-source-plugin

Hi,
I'm trying to add dynamic cdn support for my repo but I encounter this error:

  ERROR in Cannot read property 'map' of undefined
    ERROR in   TypeError: Cannot read property 'options' of undefined
      - index.js:23
        [templates_generator]/[html-webpack-inline-source-plugin]/index.js:23:36
      - new Promise
      - Hook.js:35 AsyncSeriesWaterfallHook.lazyCompileHook [as _promise]
        [templates_generator]/[tapable]/lib/Hook.js:35:21
      - index.js:673
        [templates_generator]/[html-webpack-plugin]/index.js:673:47
      - index.js:187 Promise.resolve.then.then.then.then.then.then.then.result
        [templates_generator]/[html-webpack-plugin]/index.js:187:18
      - next_tick.js:188 process._tickCallback
        internal/process/next_tick.js:188:7

Everything was working fine before I added dynamic-cdn and this is my plugins section (ignore the dynamic entry suport)
I saw in the code that this plugin applies the HTMLwbepack plugin and I suspect that this causes the inline-source-plugin to not work.

new HtmlWebpackPlugin({
        template: entry.template,
        filename: `${entry.chunkName}.html`,
        inlineSource: entry.splitBundle ? `(runtime.*.js$|DL.*.js$|${entry.chunkName}.*.css$)` : '.(js|css)$',
        inject: 'head',
        chunksSortMode: entry.splitBundle ? function (a, b) {
          let orders = ['runtime', 'DL', 'vendor', entry.chunkName]
          if (orders.indexOf(a.names[0]) > orders.indexOf(b.names[0])) {
            return 1
          } else if (orders.indexOf(a.names[0]) < orders.indexOf(b.names[0])) {
            return -1
          } else {
            return 0
          }
        } : () => 0
      }),
      new DynamicCdnWebpackPlugin({
        only: ['react', 'react-dom']
      }),

versions

"dynamic-cdn-webpack-plugin": "^4.0.0-rc.1",
"html-webpack-inline-source-plugin": "^0.0.10",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.5.0",

It would be great to be able to use both plugins,
Thanks for the hard workd on this project!

Optional and peer dependencies

I'm making a library that have optional and peer dependencies.

The end-users (developers) of my library may optionally install package styled-components or not.
But dynamic-cdn-webpack plugin always injects the optional package in the index.html, even it was not installed!

My library package.json has section optionalDependencies , so there is a way how to know which is optional and peer dependency.

Here is a project to produce the bug:

git clone [email protected]:sultan99/rol-vs-jsx.git
cd rol-vs-jsx
npm i
npm run build

After build check folder dist/rol. If you open index.html you will find it includes script with styled-components which should not be because the package is not used in the project.

image

Can you fix the bug?

feat: handle async resolver

Depends on #13

Allow resolver to return a Promise

With this feature, we will be able to handle https://cdnjs.com/ urls. Indeed, CdnJs does not make new module available straight away, so module-to-cdnjs will need to check that the url is available beforehand (or we could use the fallback?)

How can I disable/ignore the plugin for Web Workers?

Hi

I've an issue where a Web Worker tries to use a global "ng" from Angular (to extend a class), which is not present inside a worker.

How can I tell your plugin to ignore these worker-files and use the normal webpack behaviour?

kind regards,
Christian

Option for URLs for certain package

I have mobx, react, react-dom dependencies, this module generates script tags only for react and react-dom and not for the mobx.

However I know that mobx has unpkg url, how can I say this to the modules cdn plugin?

Since I know mobx has this working url: https://unpkg.com/[email protected]/lib/mobx.umd.min.js I would like to define this in the plugin, e.g:

new ModulesCdnWebpackPlugin({
  urls: { // This is made up property
    "mobx" : "https://unpkg.com/mobx@VERSION/lib/mobx.umd.min.js"
  }
})

Also I think I would like to use minified version of react so I could use this url instead:

https://unpkg.com/[email protected]/dist/react.min.js

I could define that also in the new urls property.

Manually script injections order.

Is there a way to tell the plugin the order of script injections in index.html?

react-redux has peer/optional dependency - react-dom but it is not declared in package.json. Sometime (randomly) the react-redux is being injected before the react-dom by dynamic-cdn-webpack-plugin and cause exceptions.

I have asked to add react-dom in optional dependency and even sent PR but it was refused.

feat: include options

options.include

Type: Array<string>
Default: []

List the modules that will be served by the cdn regardless if they are required or not (ie: css libraries, polyfills)


NOTE: it should fails if module not found

Is there a way to configure script injections?

I have issues with injected scripts in html.

First, some packages have an optional dependencies, before to import they check require.resolve('optional-dependency-which-end-user-may-not-install'), if the optional dependency is installed then would be called require/import.

So the dynamic-cdn-webpack-plugin miss to inject those optional packages, and the application ends with error: Module not found.

The other issue, some time dependent package is injected before the main package.

My question is, Is there a way how to force dynamic-cdn-webpack-plugin to include some packages and make script injection order?

[Propostion] New API to instantiate plugin for diff supported output plugin

I really hate this code:

const isUsingHtmlWebpackPlugin = HtmlWebpackPlugin != null && compiler.options.plugins.some(x => x instanceof HtmlWebpackPlugin);
if (isUsingHtmlWebpackPlugin) {
this.applyHtmlWebpackPlugin(compiler);
} else {
this.applyWebpackCore(compiler);
}

It's working but for the user it can be very surprising and I don't think it can be extended extensively to handle different output plugin (like #31 )

I think a better API would be to expose multiple constructor like (better name ?):

  • DynamicCdnWebpackPlugin
  • DynamicCdnWebpackPLuginForHtmlPlugin
  • DynamicCdnWebpackPluginForAssetsPlugin
  • ...

DynamicCdnWebpackPLuginForHtmlPlugin would extend DynamicCdnWebpackPLugin and would override the output function

@aulisius What do you think? Do you have any other suggestion?

Cleanup before v4 release

  • update ava
  • use native js (no build step / babel)
  • double check there is no references to pre webpack 4
    • src
    • test

feat: verbose mode

options.verbose

Type: boolean

Default: false

Log whether the library is being served by the cdn or is bundled

Should log either:

  • 'react' is being served by https://unpkg.com/[email protected]/dist/react.js
  • 'react' couldn't be find, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json

Does this webpack plugin will also work with Angular

Hi Team,

Actually, I was working on one POC where in I need to dynamically load Module and its dependencies on runtime say there are two different solutions running from different repositories hosted on different domain. So, once I request the module from domain X, it should get resolved in domain Y.

Hence, just wanted to check whether this plugin will work for angular as well or this is only meant for react.

Thanks,
Rahul

feat: work with webpack-manifest-plugin

The webpack-manifest-plugin has a generate option. I am currently using this option to dump the files required for each entrypoint to json.

I would like the dynamic-cdn-webpack-plugin to output to webpack in such a way that entrypoint.getFiles() includes the cdn urls that are required for the entrypoint.

I am doing SSR so it is not straightforward for me to use the html-webpack-plugin. I have considered that I could use this plugin to generate the script tags, but it seems like overkill.

Another workaround is to use the externals configuration in webpack, but this will make it difficult/impossible to only include the cdn urls that are needed by each chunk.

feat: only and exclude options

options.only

Type: Array<string>
Default: null

List the only modules that should be served by the cdn

options.exclude

Type: Array<string>
Default: []

List the modules that will always be bundled

NOTE: those two options cannot be set together

Support with Next.JS

Hello, I'm trying to integrate this webpack plugin with my Next.JS web application. Following is my next.config.js. It works in the production mode but not in the development mode.

Did anyone successfully integrate this plugin with the Next.JS?

const HtmlWebpackPlugin = require('html-webpack-plugin');
const DynamicCdnWebpackPlugin = require("dynamic-cdn-webpack-plugin");

module.exports = withPlugins([withTM], {
  webpack: (config, options) => {
    if (!options.isServer) {
      config.plugins.push(
        new DynamicCdnWebpackPlugin({
          only: ['react', 'react-dom']
        }),
      )
    return config;
  }
})

99.9% of my packages could not be found, but they exist in CDN

Is this suppose to be like this?
only plugin that was replaced by cdn was react-router-dom

โŒ 'lodash' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json

but
https://unpkg.com/[email protected]/ exists

'redux-form' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'dayjs' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ '@babel/runtime/helpers/inherits' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ '@babel/runtime/helpers/getPrototypeOf' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ '@babel/runtime/helpers/possibleConstructorReturn' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ '@babel/runtime/helpers/createClass' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'eventemitter3' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'prop-types' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'scriptjs' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ '@mapbox/point-geometry' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/core-js/object/get-prototype-of' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/classCallCheck' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/createClass' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/possibleConstructorReturn' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/inherits' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'react-lifecycles-compat' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'prop-types' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/extends' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/core-js/object/get-prototype-of' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/classCallCheck' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/createClass' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/possibleConstructorReturn' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/inherits' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'prop-types' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/core-js/object/keys' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/classCallCheck' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/createClass' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/possibleConstructorReturn' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/core-js/object/get-prototype-of' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/inherits' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'prop-types' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/objectWithoutProperties' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/extends' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/core-js/object/get-prototype-of' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/createClass' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/possibleConstructorReturn' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/inherits' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'react-lifecycles-compat' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'prop-types' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/classCallCheck' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/extends' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/core-js/object/get-own-property-descriptor' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
โŒ 'babel-runtime/helpers/classCallCheck' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json
....

Vendor code still in my bundle

When I run my production build, I see script tags to cdn files for all my vendor packages.

<body>
    <div id="elmish-app" class="has-navbar-fixed-top"></div>
<script type="text/javascript" src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script><script type="text/javascript" src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script><script type="text/javascript" src="https://unpkg.com/@umds/[email protected]/object-assign.min.js"></script><script type="text/javascript" src="app.afceab6591441e2febcf.js"></script></body>

However my app bundle still contains react in it. What am I missing here?

image

[Bug] Module isn't auto loaded from CDN URL at runtime. Is it meant to be?

Is this a bug report?

Yes, if the intended behaviour of this plugin is to facilitate loading external modules from CDN URL's automatically at runtime. Is it?

Environment

[email protected]
[email protected]

Steps to Reproduce

  1. Create a simple hello world app which consumes an external module

    // src/app.js
    var _ = require('lodash');
    
    var foo = ['foo', 'foo', 'foo'];
    var foobar = _.map(foo, function(item) {
        return item + 'bar';
    });
    var foobarString = JSON.stringify(foobar, null, 2);
    
    var el = document.createElement('pre');
    el.innerHTML = foobarString;
    document.body.appendChild(el);
    console.log(foobarString);
    <!-- index.html -->
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Foobar</title>
        </head>
        <body>
            <h1>Foobar</h1>
            <script src="build/app.js"></script>
        </body>
    </html>
  2. Configure plugin to load an external module from CDN using a custom resolver

    const path = require('path');
    const DynamicCdnWebpackPlugin = require('dynamic-cdn-webpack-plugin');
    const ManifestPlugin = require('webpack-manifest-plugin');
    
    module.exports = {
    
        entry: {
            app: path.resolve(__dirname, 'src/app.js')
        },
    
        output: {
            path: path.resolve(__dirname, './build'),
        },
    
        devtool: false,
    
        plugins: [
            new ManifestPlugin({
                fileName: 'webpack-manifest.json'
            }),
            new DynamicCdnWebpackPlugin({
                only: ['lodash'],
                verbose: true,
                resolver: (packageName, version, options) => {
                    if (packageName == 'lodash') {
                        return {
                            name: packageName,
                            url: 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js',
                            version: version,
                            var: '_'
                        };
                    }
                    return null;
                }
            })
        ]
    
    };
  3. Build & run
    webpack --mode=development

Expected Behavior

The external library (lodash) would be automatically loaded from the configured CDN url at runtime as "_"

Actual Behavior

The external library was not loaded automatically which resulted in a runtime error:
Uncaught ReferenceError: _ is not defined

Note that the CDN URL is referenced in the manifest JSON but not in the compiled js bundle and we see the following line in the console output for the build:
โœ”๏ธ 'lodash' will be served by https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.1.0/lodash.js

Reproducible Demo

Fiddle of the compilation result

Source Repo

Thanks in advance

doesn't parse other libraries

It parses only jquery, or some other libraries like react maybe, but it doesn't include all the libraries on the node_modules for example
import Clipboard from 'clipboard';
so, how to solve this?

Allow custom cdn config

From #1 (comment) by @Van-Nguyen

Just the plugin I was looking for, I'm surprised it does not exist anywhere else yet. Nice work so far ๐Ÿ‘

When a module is not found I'm getting this:

throw new Error(`'${moduleName}' is not available through cdn, add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json if you think it should`);

Would it be possible to add an option which can be additional to the modules.json file, rather than needing to do a pull request every time it doesn't find it.

i.e.

new ModulesCdnWebpackPlugin({
  additional: {
    "vue": {
      "var": "Vue",
      "url": "https://unpkg.com/vue@[version]/dist/vue.runtime.min.js"
    }
  },
  modules: ['vue']
})

This would make it much more flexible and less opinionated, what are your thoughts?

Cheers.

Resolving modules called from an external folder

Hi there! First of all, thanks a lot for this great plugin. I just started it and I'm impressed with the results but I have only little problem. I use it for Fable projects, a compiler from F# to JS. Because Fable is compatible with Webpack, we can import directly F# files into the bundle. However F# dependencies, unlike npm, are being downloaded to a cache folder that it's not in the project directory. Because of this when one of the modules that I want to change to CDN (say "react-dom") is being imported not from the project code, but from one of the dependencies, the contextPath will be an external folder and the call to resolvePkg in the following line fails:

const {pkg: {version, peerDependencies}} = await readPkgUp({cwd: resolvePkg(moduleName, {cwd: contextPath})});

To avoid this kind of problems I add the following to webpack.config.js:

  resolve: {
    modules: [path.join(__dirname, "./node_modules/")]
  },

Thanks to this, loaders can use this.resolve (reference) to locate modules even from folders external to the project. But apparently this function is not available for plugins or at least I couldn't find it.

I managed to fix the issue by capturing the compiler.context (e.g. this.originalContext = compiler.context) here:

execute(compiler, {env}) {
compiler.plugin('normal-module-factory', nmf => {

And then using it instead of contextPath in the line mentioned above. So my question is: would it be OK to send a PR to make an extra flag available (say options.useOriginalContext) and use the compiler.context instead of contextPath when this flag is activated?

feat: add "resolver" options to be able to use a different cdn

options.resolver

Type: string || function

Default: 'module-to-cdn' || 'module-to-jsdelivr'

Allow you to define a custom module resolver, it can either be a function or an npm module
The resolver should return either null or an object with the keys: name, var, url


Related to #3, but following a different / more modular logic

Add `module-to-cdn` as dependency

Hi,

I have tried to use dynamic-cdn-webpack-plugin in my webpack.config.js and I got following error message:

Error: Cannot find module 'module-to-cdn'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (c:\Workspace\project\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at getResolver (c:\Workspace\project\node_modules\dynamic-cdn-webpack-plugin\lib\get-resolver.js:12:12)
    at new DynamicCdnWebpackPlugin (c:\Workspace\project\node_modules\dynamic-cdn-webpack-plugin\lib\index.js:83:51)
    at Object.<anonymous> (c:\Workspace\project\front.core.config.js:73:5)
    at Module._compile (c:\Workspace\project\node_modules\v8-compile-cache\v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (c:\Workspace\project\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at WEBPACK_OPTIONS (c:\Workspace\project\node_modules\webpack-cli\bin\convert-argv.js:133:13)
    at requireConfig (c:\Workspace\project\node_modules\webpack-cli\bin\convert-argv.js:135:6)
    at c:\Workspace\project\node_modules\webpack-cli\bin\convert-argv.js:142:17
    at Array.forEach (<anonymous>)
    at module.exports (c:\Workspace\project\node_modules\webpack-cli\bin\convert-argv.js:140:15)
    at yargs.parse (c:\Workspace\project\node_modules\webpack-cli\bin\cli.js:241:39)
    at Object.parse (c:\Workspace\project\node_modules\yargs\yargs.js:563:18)
    at c:\Workspace\project\node_modules\webpack-cli\bin\cli.js:219:8
    at Object.<anonymous> (c:\Workspace\project\node_modules\webpack-cli\bin\cli.js:530:3)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:20:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1

When I manually add module-to-cdn as a dependency to the project, everything starts working as it should. I believe the easiest fixes will be just move module-to-cdn from peerDependencies to just dependencies. By that package would be automatically delivered to a calling project.

Missing dependencies

Is this a bug report?

Yup! When I tried adding 'dynamic-cdn-webpack-plugin' to my project, it causes webpack to crash trying to require in a dependency.

Please find a minimal recreation here: https://github.com/wingsbob/dynamic-cdn-webpack-plugin-issue

Environment

npm ls dynamic-cdn-webpack-plugin
[email protected] project root
`-- [email protected]
npm ls webpack
[email protected] project root
`-- [email protected]

Steps to Reproduce

require('dynamic-cdn-webpack-plugin')?

Expected Behavior

Webpack runs ๐Ÿคทโ€โ™‚

Actual Behavior

Webpack crashes with

Error: Cannot find module 'babel-runtime/core-js/object/values'

This happens on requiring 'dynamic-cdn-webpack-plugin'

Reproducible Demo

https://github.com/wingsbob/dynamic-cdn-webpack-plugin-issue

Instructions in the readme.

Does it work with CommonsChunkPlugin?

Hi,

I've an Angular4 project where I tested your plugin, but the only thing which will be cdnified is RxJS:
(part of result of index.html)

<app-root></app-root>
<script type="text/javascript" src="https://unpkg.com/[email protected]/bundles/Rx.min.js"></script>
<script type="text/javascript" src="polyfills.min.js"></script>
<script type="text/javascript" src="vendor.min.js"></script>
<script type="text/javascript" src="app.min.js"></script>

Does your plugin work with the CommonsChunkPlugin from webpack? Or did I make any mistake in my config?

Inside vendor.min.js all dependencies are still fully imported although I've a custom resolver which resolves all angular modules with unpkg.com.

The verbose log tells me:

...
โœ”๏ธ '@angular/core' will be served by https://unpkg.com/@angular/[email protected]/bundles/core.umd.min.js
โœ”๏ธ '@angular/core' will be served by https://unpkg.com/@angular/[email protected]/bundles/core.umd.min.js
โœ”๏ธ 'rxjs' will be served by https://unpkg.com/[email protected]/bundles/Rx.min.js
โœ”๏ธ '@angular/core' will be served by https://unpkg.com/@angular/[email protected]/bundles/core.umd.min.js
โœ”๏ธ '@angular/common' will be served by https://unpkg.com/@angular/[email protected]/bundles/common.umd.min.js"
โœ”๏ธ '@angular/platform-browser' will be served by https://unpkg.com/@angular/[email protected]/bundles/platform-browser.umd.min.js"
โœ”๏ธ '@angular/core' will be served by https://unpkg.com/@angular/[email protected]/bundles/core.umd.min.js
โœ”๏ธ '@angular/platform-browser' will be served by https://unpkg.com/@angular/platform-br 10% building modules 5/6 modules 1 active ...bapp-v2/src/scripts/app/app.module.tsโœ”๏ธ '@angular/core' will be served by https://unpkg.com/@angular/[email protected]/bundles/core.umd.min.js
โœ”๏ธ '@angular/platform-browser' will be served by https://unpkg.com/@angular/[email protected]/bundles/platform-browser.umd.min.js"
โœ”๏ธ '@angular/common' will be served by https://unpkg.com/@angular/[email protected]/bundles/common.umd.min.js"
...

Here is the my webpack plugin-config including the custom resolver:

// ...
plugins: [
            new DynamicCdnWebpackPlugin({
                disable: ENV !== "production",
                verbose: true,
                only: [
                    "@angular/core",
                    "@angular/common",
                    "@angular/http",
                    "@angular/platform-browser",
                    "@angular/platform-browser-dynamic",
                    "@angular/router",
                    // "node-forge",
                    // "reflect-metadata",
                    "rxjs",
                    "jquery"
                ],
                resolver: function (moduleName, version, options) {
                    var mod2Cdn = require('module-to-cdn');
                    var mod = mod2Cdn(moduleName, version, options);
                    if(mod) return mod;

                    var vars = {
                        "@angular/core": 'ng',
                        "@angular/common": 'ng',
                        "@angular/http": 'ng',
                        "@angular/platform-browser": 'ng',
                        "@angular/platform-browser-dynamic": 'ng',
                        "@angular/router": 'ng',
                        "node-forge": 'forge',
                        "reflect-metadata": 'window',
                        "rxjs": 'Rx',
                        "jquery": '$'
                    };
                    var urls = {
                        "@angular/core": 'https://unpkg.com/@angular/core@[version]/bundles/core.umd.min.js"',
                        "@angular/common": 'https://unpkg.com/@angular/common@[version]/bundles/common.umd.min.js"',
                        "@angular/http": 'https://unpkg.com/@angular/http@[version]/bundles/http.umd.min.js"',
                        "@angular/platform-browser": 'https://unpkg.com/@angular/platform-browser@[version]/bundles/platform-browser.umd.min.js"',
                        "@angular/platform-browser-dynamic": 'https://unpkg.com/@angular/platform-browser-dynamic@[version]/bundles/platform-browser-dynamic.umd.min.js"',
                        "@angular/router": 'https://unpkg.com/@angular/router@[version]/bundles/router.umd.min.js"',
                        "node-forge": 'https://unpkg.com/node-forge@[version]/dist/forge.min.js"',
                        "reflect-metadata": 'https://unpkg.com/reflect-metadata@[version]/Reflect.js"',
                        "rxjs": 'https://unpkg.com/rxjs@[version]/bundles/Rx.min.js"',
                        "jquery": 'https://unpkg.com/jquery@[version]/dist/jquery.min.js"',
                    };

                    if(!vars[moduleName]) {
                        return null;
                    }

                    return {
                        "name": moduleName,
                        "var": vars[moduleName],
                        "url": urls[moduleName].replace('[version]', version),
                        "version": version
                    };
                },
                env: 'production'
            }),
            extractCssToAssets,
            new webpack.DefinePlugin({
                'process.env': {
                    'ENV': JSON.stringify(ENV)
                }
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: ['app', 'vendor', 'polyfills']
            }),
            new webpack.ContextReplacementPlugin(
                /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
                helpers.root('src'),
                {}
            ),

            new HtmlWebpackPlugin({
                filename: 'index.html',
                template: 'src/base.html',
                chunksSortMode: 'dependency'
            })
        ],
// ...

Kind regards

Can't figure out a basic scenario working with my own CDN and packages

Basic scenario working with webpack and this package.

example:

main.ts

export class Main {
    public Init(): string {
        console.log("Init was called");
        return "Init done";
    }

    public GetDelayedMessage(): Promise<string> {
        return Promise.resolve("Thanks");
    }
}

I'm hosting "es6-promise" under my own CDN: https://cdn.company.com/libs/es6-promise.js

I can't figure out how to make webpack not bundle es6-promise but instead load it from my CDN.
Better yet - I would ultimately would like to lazy-load it only when someone called GetDelayedMessage, if the code changes to this:

    public Init(): string {
        console.log("Init was called");
        return "Init done";
    }

    public GetDelayedMessage(): Promise<string> {
        return import("es6-promise").then(() => { return "Thanks!"; });
    }
}

Could someone perhaps provide a basic webpack.config.js that covers this scenario?
I read through the documentation but can't find all the info regarding:

  1. Usage with ManifestPlugin - what is the content of "manifest.json"?
  2. options.resolver - what is the signature of this function (which parameters it gets)?

I tried to set up this plugin but that didn't work:

    resolver: function (packageName, version, params) {
        switch (packageName) {
            case "es6-promise":
                return { name: packageName, var: "Promise", url: "https://apps.kwizcom.com/libs/es6-promise/es6-promise.min.js", version: version };
        }
        return null;
    }
})

Thanks!!!

Dependency issue with babel-runtime

Is this a bug report?

Yes.

Environment

npm ls dynamic-cdn-webpack-plugin

[email protected] /home/shukant/gravitify.io
โ””โ”€โ”€ [email protected] 


npm ls webpack

[email protected] /home/shukant/gravitify.io
โ””โ”€โ”€ [email protected] 

Steps to Reproduce

My webpack.config.js file looks exactly like this:

const path = require('path');
const webpack = require('webpack');

const DynamicCdnWebpackPlugin = require('dynamic-cdn-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  mode: "production",
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "main.js"
  },
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: [path.join(__dirname, '/node_modules/')],
        use: {
          loader: 'babel-loader',
          options: {
            presets: [`@babel/preset-env`],
            plugins: [
              "@babel/plugin-minify-dead-code-elimination",
              "@babel/plugin-transform-object-set-prototype-of-to-assign"
            ]
          }
        }
      }
    ]
  },
  plugins: [
    new DynamicCdnWebpackPlugin(),
    new HtmlWebpackPlugin(),
    new webpack.ProgressPlugin()
  ],
  optimization: {
    minimizer: [
      new TerserPlugin({
        cache: true,
        parallel: true,
        terserOptions: {
          mangle: true
        }
      })
    ]
  }
}

(Write your steps here:)

  1. I just run webpack --optimize-minimize

Expected Behavior

It should build fine.

Actual Behavior

Logs error:

/home/shukant/gravitify.io/node_modules/webpack-cli/bin/cli.js:231
				throw err;
				^

Error: Cannot find module 'babel-runtime/core-js/object/values'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (/home/shukant/gravitify.io/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
    at Object.<anonymous> (/home/shukant/gravitify.io/node_modules/dynamic-cdn-webpack-plugin/lib/index.js:7:15)
    at Module._compile (/home/shukant/gravitify.io/node_modules/v8-compile-cache/v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (/home/shukant/gravitify.io/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
    at Object.<anonymous> (/home/shukant/gravitify.io/node_modules/dynamic-cdn-webpack-plugin/index.js:2:18)
    at Module._compile (/home/shukant/gravitify.io/node_modules/v8-compile-cache/v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (/home/shukant/gravitify.io/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
    at Object.<anonymous> (/home/shukant/gravitify.io/webpack.config.js:4:33)
    at Module._compile (/home/shukant/gravitify.io/node_modules/v8-compile-cache/v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (/home/shukant/gravitify.io/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
    at WEBPACK_OPTIONS (/home/shukant/gravitify.io/node_modules/webpack-cli/bin/convert-argv.js:115:13)
    at requireConfig (/home/shukant/gravitify.io/node_modules/webpack-cli/bin/convert-argv.js:117:6)

Reproducible Demo

(Paste the link to an example project and exact instructions to reproduce the issue.)

feat: fallback CDN

inspired by jso0/html-webpack-cdn-plugin#1

Depends on #13


options.fallbackResolver

Type: string || function

Default: 'module-to-cdn' || 'module-to-jsdelivr'

Similar to resolver but the module will be loaded from this CDN only if the main CDN is experiencing issues


It will create a new file which will contains for each module:

window.React || document.write('<script src="https://unpkg.com/[email protected]/dist/react.js"><\/script>');

NOTE: resolver and fallback must both return a valid cdnConfig otherwise the module is ignored

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.