简体   繁体   English

导出Webpack库

[英]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. 所以对于一个项目,我想开始使用reactjs,但是不幸的是,当前项目没有构建管道。 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 . 我想现在我可以使用WebPack,Babel和Sass设置构建管道并将其全部编译成一个包,我们将其称为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. 我可以将已编译的javascript文件链接到我们的渲染页面之一,然后我的目标是以某种方式导出组件,以便可以使用以下功能创建它。

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? export default MyExportedComponent足够?

Generally, you would call ReactDOM.render() inside your bundle.js, usually in the file that represents the entry point to your bundle. 通常,您将在bundle.js中调用ReactDOM.render() ,通常是在表示捆绑包入口点的文件中。

This means, you don't have to export anything, and can just embed bundle.js into your HTML file. 这意味着,您无需导出任何内容,只需将bundle.js嵌入到HTML文件中即可。


If you need to export something from your bundle, you could attach it to the global scope by setting an attribute on window . 如果您需要从包中导出某些内容,可以通过在window上设置一个属性将其附加到全局范围。 You should try to avoid that though. 您应该尝试避免这种情况。

I ended up changing the WebPack config to export the code as a bundle. 我最终更改了WebPack配置,以将代码导出为捆绑包。

Here is the exported bundle in the main compiled JavaScript file 这是主要的已编译JavaScript文件中的导出包

exportedLibary.js

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

And making modifications to the output parameter in the WebPack config file: 并修改WebPack配置文件中的输出参数:

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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