Skip to content

Require external (unmanaged) file #150

Closed

Description

@kaste

I would have expected that a

require.ensure(['script!//ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js'], function(require){

});

would work out-of-the-box. But it doesn't.

(I don't need this for angular, but would like to do this for some payments-gateway-js.)

Any solution for this.

Activity

  1. jhnns commented on Jan 20, 2014

    @jhnns
    Contributor

    Mhmm... loading a script from another domain is definitely not a webpack task, since webpack is basically a bundler.

    But maybe the script-loader should detect domain patterns? It's a bit complicated because the domain pattern should not conflict with a file path.

    However, this discussion should be done in the script-loader's repo

  2. sokra commented on Jan 20, 2014

    @sokra
    Member

    webpack is a module bundler not a javascript loader. It package files from local disk and don't load files from the web (except its own chunks).

    Use a javascript loader, i. e. script.js

    var $script = require("scriptjs");
    $script("//ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js", function() {
      // ...
    });
  3. jhnns commented on Jan 20, 2014

    @jhnns
    Contributor

    But the script-loader is loading the script from the home domain. Shouldn't it be possible to load stuff from another domain (given that the CORS-header are set correctly)?

  4. sokra commented on Jan 20, 2014

    @sokra
    Member

    The script-loader doesn't really add a <script> tag. It just evaluate some javascript in the global context.

  5. jhnns commented on Jan 20, 2014

    @jhnns
    Contributor

    Ah ok...

  6. kaste commented on Jan 20, 2014

    @kaste
    Author

    I just would have thought that using one of the loaders (script-loader seemed to be a good guess), it would work.

    (From the user perspective it looks like, webpack (CLI, server) is a bundler and webpack-web is basically a loader.)

  7. ThomasDeutsch commented on Jan 23, 2014

    @ThomasDeutsch

    Is it possible to use a named-AMD-module like 'jquery' or a chunk as an "external" chunk ?

    I have 2+ webpack runtimes on one page that require jquery - so, i can not use the CommonsChunkPlugin, right?
    Since webpack is a module bundler, would it somehow be possible to give one chunk a url of an external chunk or amd module?

  8. sokra commented on Jan 24, 2014

    @sokra
    Member

    @ThomasDeutsch If you want to share chunks or common modules between multiple entry points, you need to use the CommonsChunkPlugin and compile all in a single webpack pass. Do this instead of multiple webpack runtimes. Check this.

  9. m59peacemaker commented on Nov 26, 2014

    @m59peacemaker

    I wrote this simple loader, external-webpack-loader, to solve this problem.
    Is there any reason this is not the appropriate solution? I just found webpack today, so let me know if I'm not thinking correctly. Thanks!

  10. jhnns commented on Dec 1, 2014

    @jhnns
    Contributor

    Sure, you can do that (and there are probably use-cases for it). But usually it defeats the purpose of a package manager...

  11. m59peacemaker commented on Dec 1, 2014

    @m59peacemaker

    Ah! I see the light. $script is the way to go since it takes care of downloading and evaluating the external script at runtime and keeps up with what you've already downloaded so that it won't download the same script twice. Makes sense. I think I had it in my head that webpack could do that, but it is a different task altogether.

  12. jbcpollak commented on Dec 9, 2015

    @jbcpollak

    I was just looking for something like this but for fonts, not scripts. It doesn't seem common fonts are stored in npm, so rather than maintaining my own variants I was hoping I could convince webpack to download them.

    @m59peacemaker - It looks like you removed your loader project, do you still have the source?

  13. m59peacemaker commented on Dec 9, 2015

    @m59peacemaker

    @jbcpollak I haven't used webpack in a long time, so I don't know how fonts should work. My loader was bad and wrong, so I removed it.

  14. simkessy commented on Dec 22, 2015

    @simkessy

    Would it be possible to do something similar but with CSS. I'm assuming $scriptjs would only work with js files.

  15. 16 remaining items

  16. shachar-i commented on Oct 30, 2016

    @shachar-i

    Thanks @nkbt , but if I use externals, I'll have to take care of my own dependencies (which is a major reason to start using Webpack to begin with).
    This is actually what I did (use externals), but not the point I'm trying to make.

    Since bundling npm installed packages is way nicer and more Webpacky, Isn't Webpack encouraging bloated bundles by not giving a good remote CDN option for 3rd party libs???
    A half-lazy developer would just pick the easy big-bundle way. I supposed many did.
    For example, I've looked at several react-webpack tutorials. All of them encourage 'npm install react' rather than the ugly external.

  17. nkbt commented on Oct 30, 2016

    @nkbt

    I understand where you are going here, but the thing is - CDN is an app concern, not bundler. Besides, there is no such thing as good remote CDN option for 3rd party libs except maybe the recent unpkg (npmcdn). But for any reasonably loaded prod it makes sense to buy/setup your own CDN.

    I personally cannot come up with any reasonable answer to this. If you do - PR to docs would be a good point to start the discussion.

    PS: mastering your tools is always a difficult process that takes heaps of time and errors. If it is possible to reduce this time - awesome

  18. mnpenner commented on Jan 29, 2017

    @mnpenner
    Contributor

    I haven't thoroughly tested it yet, but you can use something like this to load an external script:

    const _scriptCache = new Map();
    
    /**
     * Load an external script.
     * 
     * @param {string} url Absolute URL of script to load
     * @param {string=} name Name of global variable that the script is expected to define
     * @return {Promise}
     */
    export function loadScript(url, name) {
        let promise;
    
        if(_scriptCache.has(url)) {
            // TODO: normalize URL
            promise = _scriptCache.get(url);
        } else {
            promise = new Promise((resolve,reject) => {
                let script = document.createElement('script');
                script.onerror = event => reject(new Error(`Failed to load '${url}'`));
                script.onload = resolve;
                script.async = true;
                script.src = url;
    
                if(document.currentScript) {
                    document.currentScript.parentNode.insertBefore(script, document.currentScript);
                } else {
                    (document.head || document.getElementsByTagName('head')[0]).appendChild(script);
                }
            });
    
            _scriptCache.set(url, promise);
        }
    
        return promise.then(() => {
            if(global[name]) {
                return global[name];
            } else {
                throw new Error(`"${name}" was not created by "${url}"`);
            }
        });
    }

    Usage:

    loadScript('https://js.stripe.com/v2/', 'Stripe').then(Stripe => {
        console.log('Stripe loaded!', Stripe);
    });

    The name parameter is to ensure the API you're loading actually created the global variable you were expecting (e.g. Stripe creates window.Stripe) and it avoids some IDE warnings ("Stripe is undefined").

  19. ryancwalsh commented on Mar 19, 2017

    @ryancwalsh

    I totally agree with @shachar-i 's points above at #150 (comment).

    I have spent 8 hours trying to learn Webpack today, and the docs do not clarify:

    I want to know how a Webpack website application (with multiple entry points) can manage lots of different dependencies (which I thought was the main motivation for Webpack) while also taking advantage of the fact that many people have jQuery and other popular libraries cached in their browsers because they've already visited sites that pulled them from CDNs, such as https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js.

    Why would I serve my own copies of popular libraries (e.g. bundled into the rest of my JS)? That seems like a waste of browser payload.

    But I also don't yet understand @sokra 's #150 (comment) recommending scriptJs.

    Why can't Webpack manage them CDN dependencies?

    What am I misunderstanding?

    Thanks, everyone!

  20. mnpenner commented on Mar 24, 2017

    @mnpenner
    Contributor

    @ryancwalsh

    I want to know how a Webpack website application (with multiple entry points) can manage lots of different dependencies ... while also taking advantage of the fact that many people have jQuery and other popular libraries cached in their browsers because they've already visited sites that pulled them from CDNs

    You can do this the same way you always would. Add

    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f" crossorigin="anonymous"></script>

    To the top of your page, and then use $ or window.$ in your bundle.

    Why would I serve my own copies of popular libraries (e.g. bundled into the rest of my JS)? That seems like a waste of browser payload.

    It's your choice. If you trust your CDN to always be available, don't bundle it. I personally put all my vendor/3rd party libraries in a CommonsChunk and perma-cache it. Our users only have to download this bundle once the first time they visit the site. Since it's a web-app, 99% of our users are recurring. If most of your users are new visitors, you might prefer a CDN.

    But I also don't yet understand @sokra 's #150 (comment) recommending scriptJs.
    Why can't Webpack manage them CDN dependencies?

    Because it's not webpack's job to do that for you. Its purpose is to bundle local files, not manage CDNs. It's relatively easy to add a <script src="..."> to the top of your page, use scriptjs, or create a helper function like I did. There's no need to bake that into webpack.

    What would that even look like? Supporting require('https://...') would lock up your browser while the script downloads because require is synchronous. require.ensure or import() are async and support could be added there, but it's just as trivial to create your own myExternalRequire.

  21. ryancwalsh commented on Mar 24, 2017

    @ryancwalsh

    @mnpenner Thanks for the response!! ☺

    Yes, most of my site's visitors are new and not recurring. Maybe I'm in the minority and starting to use Webpack was the wrong choice for me.

    I'm surprised more Webpack fans aren't asking for this functionality. To me, managing dependencies is important, regardless of whether the code is hosted all together locally or if some of it sits on a CDN.

    I'm not sure how to create my own myExternalRequire function to do what we're describing.

    [I'm impressed that I even got Webpack working at all—it took me more than a full day to migrate my site over (to the Webpack way). The docs are super sparse and seem like they were written as reminders to the creators of Webpack rather than to introduce new developers to it.]

  22. mnpenner commented on Mar 24, 2017

    @mnpenner
    Contributor

    @ryancwalsh I posted my implementation just a few comments up. Webpack is difficult to get started with, I'll grant you that, but it's also quite flexible. I'm sure the maintainers wouldn't mind some help on the documentation side once you get it all figured out. There's lots of blogs/tutorials on the subject if you find the official documentation too sparse.

  23. ryancwalsh commented on Mar 24, 2017

    @ryancwalsh

    @mnpenner Sweet--I don't know how I missed that. I'll check that out. Thanks!

  24. bizm commented on Apr 26, 2017

    @bizm

    Is it possible to bundle library as a module for dynamic import (https://webpack.js.org/guides/code-splitting-async/#dynamic-import-import-)?

    I just want my library code to be wrapped by webpackJsonp function (without all that webpack bootstrap) and then in a parent project i want to have import("path/to/external/library.js") which doesn't throw any "Module not found" errors.

  25. wbern commented on Jun 14, 2017

    @wbern

    I want to be able to use System.import() to import some external url's that I only want resolved during runtime.

    After scouring this page a bit: https://github.com/webpack/docs/wiki/configuration#automatically-created-contexts-defaults-modulexxxcontextxxx

    module: {
            exprContextCritical: false, // true triggers warning
            rules: [ ...
    

    However it seems like I am no longer able to import url's now.

    I tried to figure out how to disable the warning only for certain imports, like if the expression started with certain letters like "url", or if I had provided a string literal that said "http", using the remaining properties. I couldn't figure it out unfortunately. If anyone else knows how, would be happy to know!

  26. wbern commented on Jun 14, 2017

    @wbern

    Ok, I found how to import a webpack bundle from another project. The file I load wraps everything inside a define()-call, which I just had to shim to get whatever what inside it.

    fetch(appUrl).then(response => response.text()).then(function(text) {
        /* eslint-disable no-unused-vars */
        let define = (fn) => fn();
        /* eslint-disable no-eval */
        let importedModule = eval(text);
    });
    

    Edit: Turns out it was not that simple, but changing library to umd made things easier in the unmanaged bundle.

  27. MrFrankel commented on Feb 25, 2018

    @MrFrankel

    I've written a loader that allows you to expose modules from one webpack build to others via a global defined namespace, this lets you define which modules you want to share between the webpack builds and allows you to share common modules while maintaining the bundles intact.

    https://github.com/MrFrankel/share-loader

  28. yvele commented on Nov 27, 2018

    @yvele

    A possible workaround may be using __non_webpack_require__ that is is the original require function which exists in the environment before webpack comes in. See #1021 (comment)

  29. josiahruddell commented on Feb 6, 2019

    @josiahruddell

    I posted a workaround here: https://stackoverflow.com/a/54559637/39013

    This solution uses webpack's noParse configuration to make a module that exports the native require function to bundled code.

  30. pimterry commented on Feb 7, 2019

    @pimterry

    It looks like there's a few different cases being discussed here, but if you're trying to require an external file and pull it in at build time (e.g. pull it from a CDN and include it in your bundle), I wrote a blog post on how to do that using val loader: https://httptoolkit.tech/blog/bundling-remote-scripts-with-webpack/

    In short: you can write a tiny script and load it with val loader to make webpack read the latest content from the CDN on every build and include it in your bundle, so you can treat it like any other normal dependency without having to vendor it into your repo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions