简体   繁体   中英

Webpack bundle JS without React or React Dom

I'd like to use webpack to bundle my JS together for a React component but without including React or React Dom, just my own React code.

The idea is so that I can load React or React Dom separately on the webpage with RequireJS as I'm adding the component to Magento2 which uses this approach for adding JS dependencies. My thought being that if I add another component this way, I don't want to be adding the React Libraries twice.

I think I need to use a different babel loader or pass in some other options?

Here is my webpack.config

const path = require('path');
const autoprefixer = require('autoprefixer');
const webpack = require('webpack');

module.exports = {
    devtool: 'cheap-module-source-map',
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'web'),
        filename: 'js/react-component.js',
        publicPath: ''
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            }
        ]
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin()
    ]
}

It works but as I said it includes the full react libraries in the generated js/react-component.js file. Any advice how I can do this?

As @Aaqib pointed out I needed to add this config options to webpack.

externals : {
  react: 'react',
  reactDom: 'react-dom'
}

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