Skip to content
Advertisement

How to compile the JS file to use a React component in a WordPress theme if I do not need SSR?

I have a WordPress theme and for a part of it I want to use a React component (I don’t need SSR). I have used create-react-app in the past but now I have this code:

JavaScript

and it does not work. The request to runtime-main.39639aca.js succeeds but it does not load my nav bar.

The issue is that create-react-app produces more than a JS file, and I need just a JS file that I can put in the theme.

I have tried some things with webpack without success. I searched on GitHub and there are some things, I do not know which one to try. I tried react-embedded and it threw me an error. I also tried this but it does not work for me.

I also dislike the ES Lint warnings (I use VS Code).

Update 1

This command does what I want, partially:

JavaScript

This is how I’ve tried without WebPack, but the editor in VS Code is filled with red squiggles although it compiles well, and I cannot import npm modules. Is there a way to be able to import npm modules? Autocompletion makes me a lot more productive.

Advertisement

Answer

I gave Rollup a try and it works beautifully.

I get some warnings in the DevTools console but it works! With autocompletion and npm module includes.

Based on this gist I have these files:

src/index.tsx

JavaScript

package.json

Just two additional scripts:

JavaScript

The unusual dependencies when compared with the gist linked above:

JavaScript

rollup.config.js

JavaScript

tsconfig.json

JavaScript

For React to work with this I have the special line: "allowSyntheticDefaultImports": true.

../footer.php

JavaScript

This helped a lot: https://github.com/hybridsjs/hybrids/issues/27#issuecomment-452346986

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement