Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How do I use React component globally?

I've made an NPM package for react, it's working fine on Node but it's not working on browser without node.

if I import within node like this:

import Progress from 'package-name'

// jsx
<Progress /> //working fine

It's working fine.

But if I use it from CDN like unpkg, it's not working.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>

// Package Script
<script src="https://unpkg.com/@delowar/[email protected]/lib/Progress.js"></script>

<script>
    ...react code...
    <Progress />
    ...react code...
</script>

It's showing an error:

Progress is not defined

enter image description here Can anyone please help me about this issue?

Webpack Configuration:

var path = require('path');

module.exports = {
    mode: 'production',
    entry: './src/Progress.js',
    output: {
        path: path.resolve('lib'),
        filename: 'Progress.js',
        libraryTarget: 'umd',
        library: 'lib',
        umdNamedDefine: true,
        globalObject: `(typeof self !== 'undefined' ? self : this)`
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules)/,
                use: 'babel-loader'
            }
        ]
    }
}

Original Repo: https://github.com/delowardev/react-circle-progressbar

like image 791
Delowar Hosain Avatar asked Oct 16 '22 06:10

Delowar Hosain


1 Answers

Change the value of library to the name of your component library: 'Progress' and add libraryExport: 'default' to assign the default export to the library target:

output: {
  path: path.resolve('lib'),
  filename: 'Progress.js',
  library: 'Progress',
  libraryTarget: 'umd',
  libraryExport: 'default',
  umdNamedDefine: true,
  globalObject: `(typeof self !== 'undefined' ? self : this)`
},

Working example:

function App() {
  return (
    <Progress />
  )
}

ReactDOM.render( <App /> , document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>

<script src="https://rawcdn.githack.com/fraction01/react-circle-progressbar/0957fed54db16a3f7b9d625711ed3961f3b34371/lib/Progress.js"></script>
<div id="root"></div>
like image 69
Fraction Avatar answered Oct 27 '22 11:10

Fraction