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:
src/index.tsx
import * asReactfrom"react";
import { render } from'react-dom';
constApp = () => {
return<buttononClick={() => alert('React from WordPress !')}>Cool!!!</button>;
};
window.addEventListener('DOMContentLoaded', () => {
render(<App />, document.getElementById('react-nav-bar'));
});
package.json
Just two additional scripts:
"build":"rollup -c","watch":"rollup -cw"
The unusual dependencies when compared with the gist linked above:
"@rollup/plugin-commonjs": "^18.0.0",
"@rollup/plugin-node-resolve": "^11.2.1",
"rollup-plugin-typescript": "^1.0.1",
rollup.config.js
import typescript from'rollup-plugin-typescript';
import resolve from'@rollup/plugin-node-resolve';
import commonjs from'@rollup/plugin-commonjs';
exportdefault {
input: './src/index.tsx',
output: {
file: './dist/bundle.js',
},
format: 'iife',
plugins: [ resolve(), typescript(), commonjs() ],
};
tsconfig.json
{"compilerOptions":{"emitDecoratorMetadata":true,"experimentalDecorators":true,"forceConsistentCasingInFileNames":true,"jsx":"react","module":"es6","moduleResolution":"node","noImplicitAny":true,"outDir":"./dist","preserveConstEnums":true,"target":"es5","allowSyntheticDefaultImports":true},"exclude":["node_modules"]}
For React to work with this I have the special line: "allowSyntheticDefaultImports": true
.
../footer.php
<divid="react-nav-bar"></div><script>try { process.env.NODE_ENV } catch(e) { var process = { env: { NODE_ENV: 'production' } }; }</script><scriptsrc="<?php echo get_template_directory_uri() ?>/react-nav-bar/dist/bundle.js"></script>
This helped a lot: https://github.com/hybridsjs/hybrids/issues/27#issuecomment-452346986
Post a Comment for "How To Compile The Js File To Use A React Component In A Wordpress Theme If I Do Not Need Ssr?"