Accessing webpack bundled libraries in the browser

后端 未结 3 885
余生分开走
余生分开走 2021-02-05 07:59

I\'m having trouble accessing a webpack bundled library from the browser.

Example: I have a class Foo

// foo.js

\"use strict\";

export de         


        
相关标签:
3条回答
  • 2021-02-05 08:37

    To make this code re-usable, you need to tell webpack you are authoring a Library.

    From the webpack documentation:

    To make your library available for reuse, add library property in webpack configuration.

    To create your library, make the following change:

    module.exports = {
      entry: './src.js',
      output: {
        path: '.',
        filename: 'bundle.js',
        library: 'fooLibrary', //add this line to enable re-use
      },
    ...
    

    In order to use the library, you can then reference it in your other scripts:

    <script type="text/javascript">
      var x = new fooLibrary.Foo();
      console.log(x);
    </script>
    
    0 讨论(0)
  • 2021-02-05 08:49

    One of the major advantages of Webpack and ES2015 modules is that it stops polluting the global namespace by default.

    Because of this, if you want to publish something on the global object, you have to do it explicitly. I recommend namespacing your classes to something unique to the application or company, so you don't risk a naming collision with anything else.

    0 讨论(0)
  • 2021-02-05 08:52

    Looks like 'var' is the default for output.libraryTarget therefore you should be able to define your output.library property and you will be able to access the var globally. https://webpack.js.org/configuration/output/#output-librarytarget

    0 讨论(0)
提交回复
热议问题