Search code examples
webpackpreact

Preact from Webpack externals


Problem

  • I need to replace the webpack externals of react with preact but only on production.
  • I need a way to verify that my package is using preact not react.

For example, on my page I would have these scripts

  • <script src="./externals.js"></script>
  • <script src="./title-component.js"></script>

In my npm react component package

  • My npm package, written in react, should work with my preact external script.
class Title extends React.Component {
  render(){
    return <h1>Test</h1>
  }
}

In Webpack prod config

  • As per the preact documentation, I added the aliases
resolve: {
    alias: {    
        "react": "preact/compat",
        "react-dom/test-utils": "preact/test-utils",
        "react-dom": "preact/compat"
    };
}

In Webpack externals

  • As recommended in module bundling my build does not contain React but rather lists it as a peer dependency.
      react: {
            root: ['React'],
            commonjs2: 'react',
            commonjs: 'react',
            amd: 'react'
        },
        'react-dom': {
            root: ['ReactDom'],
            commonjs2: 'react-dom',
            commonjs: 'react-dom',
            amd: 'react-dom'
        },

Any help will be appreciated.


Solution

  • a way to verify that my package is using preact not react

    Look at the compiled & un-minified code to see how the components' functions are called:

    React: _jsxs() or React.createElement()

    Preact: Preact.h() ( or maybe just h()? )

    ref: @babel/plugin-transform-react-jsx