简体   繁体   中英

Exporting a library for webpack

So for a project I want to start using reactjs but unfortunately the current project doesn't have a build pipeline. I think for now I can just set up a build pipeline using WebPack, Babel, and Sass and compile that all into a bundle, let's call that bundle.js . I can link that compiled javascript file into one of our rendered pages and then my goal is to export the component somehow so that I can create it using the following function.

ReactDOM.render(
  React.createElement(MyExportedComponent, {prop: 'prop'}, null),
  document.getElementById('root')
);

What would be the proper way to export the class?

Is export default MyExportedComponent enough?

Generally, you would call ReactDOM.render() inside your bundle.js, usually in the file that represents the entry point to your bundle.

This means, you don't have to export anything, and can just embed bundle.js into your HTML file.


If you need to export something from your bundle, you could attach it to the global scope by setting an attribute on window . You should try to avoid that though.

I ended up changing the WebPack config to export the code as a bundle.

Here is the exported bundle in the main compiled JavaScript file

exportedLibary.js

module.exports = {
    someRender: (element) => {
        ReactDom.render(
             <div>Hello</div>
        );
    }
}

And making modifications to the output parameter in the WebPack config file:

webpack.config.js

output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'someDir'),
    library: 'RenderComponent'
}

Now we can use the exported library in any of our projects.

someProject.html

<script src="someDir/bundle.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM