Skip to content

Exclude react from bundle, and include it directly from the layout #1275

Closed

Description

@YoussefTaghlabi

I'm including React directly from my layout, and I would like webpack to exclude it from the bundle, and make react refers to the window global object React

I'm using the following:

{
        ...
        externals: {
            // Use external version of React
            "react": "React"
        },
        plugins: [
            new webpack.IgnorePlugin(/react/)
        ]
        ...
}

react gets excluded from the bundle, but client side I'm getting Uncaught Error: Cannot find module "react".

Any hints?

Activity

  1. changed the title [-]Exclude react from bundle, and including it directly from the layout[/-] [+]Exclude react from bundle, and include it directly from the layout[/+] on Jul 22, 2015
  2. xusiyuan841028 commented on Jul 22, 2015

    @xusiyuan841028

    @YoussefTaghlabi Do you add <script> tag in your page?

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
    <script type="text/javascript" src="/scripts/app.bundle.js"></script>
    
  3. YoussefTaghlabi commented on Jul 22, 2015

    @YoussefTaghlabi
    Author

    @xusiyuan841028 Yep, I do. But webpack is looking for react while on my page I have React.
    Even having window.react = React right after loading my React script from CDN doesnt solve it.
    Internally webpack is returning Uncaught Error: Cannot find module "react"

  4. IngwiePhoenix commented on Jul 22, 2015

    @IngwiePhoenix

    Solution:

    • Create a JS file called dummyReact.js

    • Fill that with these contents:

      module.exports = window.React;

    • Now add an alias in your config.webpack.js

      "react": "dummyReact.js"

    • Make sure your react is loaded before the WebPack bundle, and this should work.

    In addition, you can also use the ProvidePlugin in conjunction with the dummyReact.js.

  5. YoussefTaghlabi commented on Jul 22, 2015

    @YoussefTaghlabi
    Author

    Thanks @IngwiePhoenix , the following did work indeed:

    {
        ...
        resolve: {
            extensions: ['', '.js'],
            alias: {
                "react": "dummyReact.js"
            }
        },
        ...
        externals: {
            // Use external version of React
            "react": "React"
        },
        ...
        module: {
            noParse: [ "react" ]
        }
    }
    

    I had to remove new webpack.IgnorePlugin(/react/) for it to work as it seems webpack completely ignores anything that has to do with react.

    My next question, how can I make use of ProvidePlugin in this use case?

  6. IngwiePhoenix commented on Jul 22, 2015

    @IngwiePhoenix

    Straight from the docs:

    plugin ProvidePlugin
    This plugin makes a module available as variable in every module. The module is required only if you use the variable.

    Example: Make $ and jQuery available in every module without writing require("jquery").

    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": "jquery"
    })

    http://webpack.github.io/docs/shimming-modules.html#order-of-loaders

    I use it exactly like that for jQuery and other modules. Use something like this for React, maybe.

    new webpack.ProvidePlugin({
        React: "React", react: "React", "window.react": "React", "window.React": "React"
    })
    

    ProvidePlugin correctly resolves aliases too. So if you just add the plugin like os, itll "just work" :)

  7. YoussefTaghlabi commented on Jul 22, 2015

    @YoussefTaghlabi
    Author

    Perfect!
    Thanks @IngwiePhoenix !

  8. IngwiePhoenix commented on Jul 22, 2015

    @IngwiePhoenix

    If you wonder how exactly this affects your code:

    var $ = require("jquery");
    reuqire("jquery-plugin");
    require("other-plugin");
    
    code();
    
    // VS.
    
    code();

    Combining Alias and Provide, you are able to pretty much reduce the amount of "startup" code you write - effectively saving yourself lines of code (which in turn saves bytes with Uglify).

  9. IngwiePhoenix commented on Jul 22, 2015

    @IngwiePhoenix

    @YoussefTaghlabi Very welcome. =)

  10. YoussefTaghlabi commented on Jul 22, 2015

    @YoussefTaghlabi
    Author

    That works really well!!
    One more thing, is there anyway we can get rid off dummyReact.js and somehow directly export window.React from webpack?
    Now that it's working, I'm trying to make it graceful :)

  11. IngwiePhoenix commented on Jul 22, 2015

    @IngwiePhoenix

    I have no idea how to achieve this, sorry. :) But this is actually a graceful soltution imo. But if you ever find something, feel free to post it.

  12. YoussefTaghlabi commented on Jul 22, 2015

    @YoussefTaghlabi
    Author

    I sure will. Thanks for your help!

  13. sokra commented on Jul 22, 2015

    @sokra
    Member
    {
            ...
            externals: {
                // Use external version of React
                "react": "React"
            },
           ...
    }

    should be enough

  14. YoussefTaghlabi commented on Jul 22, 2015

    @YoussefTaghlabi
    Author

    either external or ProvidePlugin works in conjunction with alias.

  15. 7 remaining items

  16. bebraw commented on Aug 11, 2016

    @bebraw
    Contributor

    @aft-luke Great to hear!

  17. buildbreakdo commented on Sep 8, 2016

    @buildbreakdo

    So which is it..

      externals: {
        react: 'react',
        'react-dom' : 'react-dom',
      }

    or

     externals: {
        react: 'React',
        'react-dom' : 'ReactDOM',
      }

    Seeing the following in the console.

    There is another module with an equal name when case is ignored.
    This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
    Rename module if multiple modules are expected or use equal casing if one module is expected.

    Curious because different solutions seem to be working for different folks (presumed via the thumbs up) and I am not understanding why..

  18. buildbreakdo commented on Sep 8, 2016

    @buildbreakdo

    Okay so here is the solution that worked for me.. all credits to @Download

    In webpack.config.js you can apparently pass an object..

      externals: {
            react: {
                root: 'React',
                commonjs2: 'react',
                commonjs: 'react',
                amd: 'react'
            },
            'react-dom': {
                root: 'ReactDOM',
                commonjs2: 'react-dom',
                commonjs: 'react-dom',
                amd: 'react-dom'
            }
        }

    Download/react-mdl@755c568

  19. Download commented on Sep 9, 2016

    @Download

    Thanks for the credits @buildbreakdo and glad it's working for you now.

    Basically what is happening here is that there are different conventions on different systems:

    On the web, libraries normally export to the window object. E.g. react to window.React, react-dom to ReactDOM etc. On Node on the other hand, we require the dependencies by package name.

    Many people that are writing React applications are only using it on the client side. They set output.target to 'web' and only need to list the web method (grab from root) in their externals config. However if you target more than one environment, you need separate externals configs for each environment. React MDL targets the 4 environments listed above.

    Edit:
    For completeness, have a look at the docs on externals. Specifically, the table below it shows for each possible externals type what the resulting import statement looks like. So if you know where it should be coming from, you can work backwards to determine which externals type you need.

  20. jaredreich commented on Sep 12, 2016

    @jaredreich

    Just to add my two cents, this did the trick for me:

    output: {
      ...
      libraryTarget: 'umd'
    },
  21. neopostmodern commented on Sep 16, 2016

    @neopostmodern

    Another two cents: If you feel like you've done all the right things and it still doesn't work, maybe it's actually not your fault but one of your dependencies includes a react addon (e.g. material-ui).
    As they [Facebook] state in a bug report, they'll ignore the exclusion. But by adding even more webpack configuration you can work around that too:

    externals: {
      ...
      'react-addons-transition-group': {
        commonjs: 'react-addons-transition-group',
        commonjs2: 'react-addons-transition-group',
        amd: 'react-addons-transition-group',
        root: ['React','addons','TransitionGroup']
      }
    }
    
  22. AZaviruha commented on Dec 17, 2017

    @AZaviruha

    If you are using lerna and "monorep", and building packages with webpack - this may help:
    lerna/lerna#1049

    alias: {
                react: path.resolve(__dirname, "node_modules/react")
            }
  23. ycscholes commented on Jan 24, 2018

    @ycscholes

    @jaredreich , Work for me

  24. abhchand commented on Oct 28, 2019

    @abhchand

    I'm getting the below error when using noParse: ['react'] as noted above:

    Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
     - configuration[0].module.noParse[0]: The provided value "react" is not an absolute path!
       -> An absolute path, when the module starts with this path it is not parsed
    
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