I have a big old website that I am adding react components to. It uses node/express and handlebar templates mostly. Basically I do it like this:
The site imports react libs in the old way (in an html file):
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
And then I use it like this:
HTML:
<div id="react-container"></div> <script src="react-component.jsx" type="text/babel"></script>
react-component.jsx:
const Component = ()=>{ ... } const container = document.getElementById("react-container"); ReactDOM.render(React.createElement(Component), container);
The issue is if I want to import libraries, they have to be available from CDN via script tags. I have found a couple now that aren’t and also it would be nice to be able to see what I’m importing at the top of a file instead of just having a bunch of libraries floating around on the window
object.
Anway, I can’t use create-react-app but I’m wondering how I can go about inserting a small build step into my system to make it possible to npm/yarn install libs and then import them into my code.
Thanks.
Advertisement
Answer
I am not familiar with the technologies you’re using but I thought your question was interesting and I looked a bit into it.
Here is what I would try to do:
Since you’re using node you could use Webpack to bundle each of your react components in its own separate file (https://webpack.js.org/concepts/output/#multiple-entry-points) and tell Webpack to put the generated files in a folder that can be served by express. (https://expressjs.com/en/starter/static-files.html). Webpack will take care of bundling all the dependencies that you might install using
npm
. You just need to expose the component to thewindow
by exporting it so that it can then be accessed by step 2.You could then use a
<script>
to load the component bundle you need in a specific template and then render it usingReactDOM.render(React.createElement(YourComponent), document.getElementById('the-container'))
.
If you’re not familiar with Webpack you can take a look at this article: https://www.valentinog.com/blog/webpack/#how-to-set-up-react-webpack-5-and-babel-from-scratch
I did not test this so I’m not sure it works but as I said I thought it was an interesting question and I want it to give it a go and maybe give you some useful ideas.