Unable to load and display a frontend React element loaded as a third-party script

Viewed 26

I'm trying to build a tool that will utilize local storage to read/write some data about a session when a user visits my website.

Ultimately I'd like to display this information back to the user as a fixed div or "window" on the page that would just display the values stored in localStorage.

Given that I'm comfortable in React, I'd like to use React to build the display window portion of this project. (Again, it would ideally just be reading/writing to localStorage, seems simple enough.)

The caveat though is that I won't be using it in a full React application. The pre-existing website I want to display the window on is vanilla js/html/css.

So I was hoping that I could utilize a tool like Webpack to export/bundle the React app Component portion as a single js file, which I would load and initiate display of like any other third-party javascript library.

<script
  async
  src="//www.mysite.org/frontend-bundle.js"
></script>

However...all my attempts at this have been failures.

At this point, I'm back at square one. I'm trying to use create-react-app to spin up a fresh React app and this is what I'd like to display in the window on the site just as a proof of concept.

I have updated my npm scripts to first do a React build. Then take all of the built .js files and bundle them as a single js file. The webpack.config.js for that looks like this:

const path = require("path")
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
const glob = require("glob")

module.exports = {
  entry: {
    "bundle.js": glob.sync("build/static/?(js|css)/*.?(js|css)").map(f => path.resolve(__dirname, f)),
  },
  output: {
    filename: "build/static/js/bundle.min.js",
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  plugins: [new UglifyJsPlugin()],
}

This seems to be building properly and to test, I've added a basic console.log('Hello, World!'); inside the main App.js to let me know it's been loaded. I see this console log when I view the source of the bundle file.

However, when I load this bundle file from the server as a <script> tag on the page, I see the file loads fine in the browser networking tab, but no console log. Nothing executes, and nothing is rendered.

Is there something obvious I'm missing and/or should I be thinking about this in a totally different way?

Appreciate any insight!

0 Answers
Related