1 year ago

#377619

test-img

Mantas

Webpack bundled library does not compile in React

I'm trying to bundle a standalone library with Webpack (v5) and use it in my React application.

The webpack.config.js file is pretty straightforward:

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

module.exports = {
  entry: './TestWebpack.js',
  mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
  output: {
    filename: 'widgets.bundle.js',
    path: path.join(__dirname, '..', 'ClientApp', 'src', 'dynamicBundles'),
    library: {
      name: 'widgets',
      type: 'umd',
      umdNamedDefine: true,
    }
  },
  externals: {
    'react': {
        'commonjs': 'react', 
        'commonjs2': 'react', 
        'amd': 'react',
        'umd': 'react'
      },
    'react-dom': {
        'commonjs': 'react-dom',
        'commonjs2': 'react-dom',
        'amd': 'react-dom',
        'umd': 'react-dom'
    }
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-react'
            ],
          }
        }
      },
    ]
  },
};

The TestWebpack.js file is also very simple:

import React from 'react';

export default function TestWebpack(){
    return (
        <div>Test</div>
    )
}

But when I compile it with Webpack and use it in my React application like this:

import React from 'react'
import { useEffect } from 'react'
import * as Widgets from '../dynamicBundles/widgets.bundle'

export default function TestUsingWebpack(){
    useEffect(() => {
        console.log('Object.keys(Widgets) - ', Object.keys(Widgets));
    }, []);

    return <div>Test</div>
}

I get the following errors:

  Line 12:  'define' is not defined   no-undef
  Line 13:   'define' is not defined   no-undef
  Line 18:   Unexpected use of 'self'  no-restricted-globals

I can't figure out how to solve this. I see in the bundled file that in these lines an undefined variable 'define' is used. I saw in other answers that people put lines at the start to define it properly, but this bundle may change frequently so it's not an answer.

Maybe there's something wrong with my Webpack config file? I'm new to this and tried following the newest articles and Webpack documentation about standalone library but it's still not working.

javascript

reactjs

webpack

webpack-5

0 Answers

Your Answer

Accepted video resources