使用React& amp;编写可嵌入的Javascript插件的WebPack [英] Writing embeddable Javascript plugin with React & Webpack

查看:116
本文介绍了使用React& amp;编写可嵌入的Javascript插件的WebPack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将我的React应用程序与Webpack捆绑在一起,以便放入CDN的分布式副本可以通过一堆与客户端相关的配置来源,调用和初始化。

I want to be able to bundle my React app with Webpack such that distributed copies put onto a CDN can be sourced, called and initialised with a bunch of config relevant to a client.

阅读这个,我正在设置我的webpack条目文件如下:

After reading this and this, I'm setting up my webpack entry file as follows:

// ... React requires etc.

(() => {
  this.MyApp = (config) => {
    // some constructor code here
  }

  MyApp.prototype.init = () => {
    ReactDOM.render(<MyReactApp config={MyApp.config} />, someSelector);
  }
})();

我的客户可以做以下事情:

The idea being that in my client, I can do something like the following:

<script src="./bundle.js" type="text/javascript"></script>
<script type="text/javascript">
  MyApp.init({
    some: "config"
  });
</script>

我的 MyApp #init 函数将呈现我的React应用程序位于客户端的某个容器中。

And my MyApp#init function will render my React app inside some container on the client.

我是否以正确的方式思考这个问题?是否有更简单或更有效的方法来解决这个问题?

Am I thinking about this in the right way? Is there a simpler or more efficient way to go about this?

我的错误是未捕获TypeError:无法设置未定义属性'MyApp',因为IIFE内的 undefined 。我真的很想了解为什么会发生这种情况以及如何解决它的建议。

My error is Uncaught TypeError: Cannot set property 'MyApp' of undefined, since this inside the IIFE is undefined. I'd really like to understand both why this is happening and advice on how to fix it.

提前致谢!

推荐答案

所以我找到了一个解决方案,如上所述这里

So I kind of found a solution to this, as described here

如果我改变我的 webpack.config.js 文件将以下属性添加到输出对象,即

If I change my webpack.config.js file to add the following attributes to the output object, i.e.

var config = {
  // ...
  output: {
    // ...
    library: 'MyApp',
    libraryTarget: 'umd',
    umdNamedDefine: true,
  }
}

此指定我正在将webpack捆绑为UMD模块的文件,所以如果我在该文件中有一个函数并将其导出...

This specifies the file I'm bundling with webpack as a UMD module, so if I have a function in that file and export it...

export const init = (config) => {
  ReactDOM.render(<MyReactApp config={config} />, someSelector);
}

然后我可以在我的客户端执行以下操作。

I can then, in my client, do the following.

<script src="./bundle.js" type="text/javascript"></script>
<script type="text/javascript">
  MyApp.init({
    some: "config"
  }); 
</script>

我的React应用呈现。

And my React app renders.

如果有人认为这是一种愚蠢的做法,我很乐意听到它!

If anyone thinks this is a daft way of doing it, I'd love to hear it!

这篇关于使用React&amp; amp;编写可嵌入的Javascript插件的WebPack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆