简体   繁体   English

Webpack + React:可重用组件未定义

[英]Webpack + React : reusable component is not defined

I'm trying to create a React component DynamicCollection which I want to use multiple times in the same page. 我正在尝试创建一个React组件DynamicCollection ,我想在同一页面中多次使用它。

What I'd like is a file dynamicCollection.js from dynamicCollection.jsx and few files which use the component DynamicCollection like this : 我想要的是来自dynamicCollection.jsx的文件dynamicCollection.js,以及一些使用组件DynamicCollection的文件,如下所示:

  • dyna1.js with ReactDOM.render(<DynamicCollection p1=... p2=.../>,document.getElementById(dyna1)); 带有ReactDOM.render(<DynamicCollection p1=... p2=.../>,document.getElementById(dyna1));
  • dyna2.js with ReactDOM.render(<DynamicCollection p1=... p2=.../>,document.getElementById(dyna2)); 带有ReactDOM.render(<DynamicCollection p1=... p2=.../>,document.getElementById(dyna2));

... ...

In dynamicCollection.jsx I've got this : 在dynamicCollection.jsx中,我得到了:

export default class DynamicCollection extends React.Component { ... }

And finally in the webpack.config.js : 最后在webpack.config.js中:

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, './build');
var APP_DIR = path.resolve(__dirname, './app');

var config = {
    entry: {
        'DynamicCollection': './app/DynamicCollectionBox.jsx',
        'dyna1': './app/dyna1.js',
        'dyna2': './app/dyna1.js',
    },
    output: {
        path: BUILD_DIR,
        filename: '[name].js'
    },
    module : {
        loaders : [
        {
            test: /\.jsx?/,
            loader : 'babel?presets[]=es2015'
        }
      ]
    }
};

module.exports = config;

The problem is that I get this error in the browser console : 问题是我在浏览器控制台中收到此错误:

ReferenceError: DynamicCollection is not defined ReferenceError:未定义DynamicCollection

(Note : I included DynamicCollection.js, dyna1.js and dyna2.js in the html file) (注意:我在HTML文件中包含了DynamicCollection.js,dyna1.js和dyna2.js)

Can you help please ? 你能帮忙吗?

Thank you in advance ! 先感谢您 !

Ok. 好。 I found the answer to this. 我找到了答案。 What I did was introduced the below attributes in webpack output; 我所做的是在webpack输出中介绍了以下属性;

library: 'ReactWelcomeComponent',
libraryTarget: 'var'

Then in my angular directive I am able to access the react component like below; 然后,在我的角度指令中,我可以访问如下所示的react组件;

var JSXReactComponent = React.createFactory(ReactWelcomeComponent.default);

With this approach, I am able to call the React component that was generated as part of webpack step and access in angular context. 通过这种方法,我可以调用作为webpack步骤的一部分生成的React组件,并在有角度的上下文中进行访问。

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

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