简体   繁体   中英

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.

What I'd like is a file dynamicCollection.js from dynamicCollection.jsx and few files which use the component DynamicCollection like this :

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

...

In dynamicCollection.jsx I've got this :

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

And finally in the 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

(Note : I included DynamicCollection.js, dyna1.js and dyna2.js in the html file)

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;

library: 'ReactWelcomeComponent',
libraryTarget: 'var'

Then in my angular directive I am able to access the react component like below;

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.

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