NotFound
NotFound

Reputation: 6172

React app injecting into js instead of index.html

I would like to create a React app that will not be a standalone site, but rather an extension to an existing site. The site is built using asp.net and I cannot make edits to it. I do have an entry with javascript and can run code such as the following:

$(document).onload(() => {
  $(body).parent().append(`
    <script src='{...}'></script>      
  `);
});

Is there any way I can change the standard Index.html output from the default create-react-app to a .js file and have the react chunks added into the append? It does not necessarily need to follow the above direction, but it's as far as I got.

Upvotes: 2

Views: 1047

Answers (1)

Sam
Sam

Reputation: 2341

I believe you could just attach it to the body using ReactDOM.render

ReactDOM.render(
  <React>
    <App />
  </React>,
  document.getElementByTagName('body')
)

But you might have to switch away from create-react-app to using webpack, and then use something like HTMLWebpackPlugin within your webpack.config.js to specify the entry point

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  target: 'web',
  mode: 'development',
  entry: './src/index.jsx',
  devtool: "source-map",
  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
    filename: "[name]/[name].js",
  },
  ...
      new HtmlWebpackPlugin({
        template: './html/index.html',
        filename: './index.html'
      }),
  ...
}

You would have to install html-webpack-plugin as well as webpack and anything you need with npm install html-webpackplugin webpack ...


If you look up tutorials on this, try to find React 17 and Webpack 5 they're fairly new. Webpack 5 has some differences with hot reloading compared to Webpack 4

Upvotes: 1

Related Questions