Configuring webpack for live reloading and Hot Module Replacement on static pages

The title of this post may not be very clear, but I appreciate your patience.

I am currently in the process of setting up React for an older Rails application that uses static ERBs. Due to the size of the project, I am gradually transitioning towards a Single Page Application (SPA) architecture by replacing components on different pages.

My current setup involves using webpack to compile a bundle file and output it to the assets directory. I then load this bundle file on the page, relying on the assets pipeline for caching (not the most ideal setup, but sufficient for now). For pages containing React components, I have <div> elements where specific components will be appended. For example:

<body>
  <div>some other ERB, HTML stuff</div>
  <div>more other ERB, HTML stuff</div>

  <div id='react-component-1'></div>
  <div id='react-component-2'></div>
</body>

This setup works as a basic foundation. However, to speed up development, I would like to implement hot module reloading (HMR). But since I am not serving the entire page, I need to write the bundle file to disk so Rails can access it. This also means I cannot use webpack-dev-server.

Is there a way to set up HMR in this kind of configuration?

Potential options include:

  1. Reloading the bundle file periodically (I've tried appending a new script tag and removing the old one, but while the script file is downloaded with a status code of 200, the updated scripts are not being loaded)
  2. Programmatically refreshing the page and storing serialized state in session storage (less than ideal, as it refreshes other parts of the static page as well)
  3. Exploring a method to only serve the bundle file through webpack-dev-server

Edit

After following @SamHH's answer, it seems the bundle file is unable to load (404 error). There might be an issue with my path configuration.

In my webpack configuration, the output path is set to:

'../../app/assets/webpack/admin'

The publicPath is set to:

/admin/

Although I attempted to match these paths in the proxy option, it didn't work as expected. From the network tab, it appears that the file was being loaded from /javascripts/...

Here is a snippet of my webpack config:

const config = {
  entry: {
    bundle: './apps/appsRegistration',
    vendor: VENDOR_LIBS
  },
  output: {
    filename: '[name].js',
    path: pathLib.resolve(__dirname, '../../app/assets/webpack/admin'),
    publicPath: '/admin/'
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor'
    }),
  ],
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: 'babel-loader',
        exclude: /node_modules/,
      },
    ],
  },
  externals: {
    react: 'React',
    'react-dom': 'ReactDOM',
    redux: 'Redux',
    'react-redux': 'ReactRedux',
    'redux-thunk': 'ReduxThunk'
  },
  devServer: {
    port: 9000,
    disableHostCheck: true,
    proxy: {
      '!/admin/**': {
        target: 'http://localhost:3000',
        secure: false
      }
    },
    hot: true
  }
};

Answer №1

To streamline your development process, consider using webpack-dev-server in conjunction with proxying non-assets back to your Rails application. This means that if your Rails app is located at http://localhost:8000, you can configure your Webpack settings to redirect any devServer requests that do not pertain to assets to this address. By doing so, you can seamlessly work on the Webpack dev server port.

For instance, by defining your Webpack config with

output.publicPath: '/dev-assets/'
, you can implement the following setup:

devServer: {
    port: 9000,
        proxy: {
            '!/dev-assets/**': {
                target: `http://localhost:8000`,
                secure: false
            }
        },
        hot: true
    },
}

Simply access http://localhost:9000 while developing in order to view your changes in real time.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Cross Origin Policy Restrictions with Fiddler for JSON Debugging

In the process of creating a modern webapp using JSON data, I came across a helpful blog post about using Fiddler to mock JSON data. My development setup involves working locally with Notepad++ and testing primarily on Chrome, with plans to expand to othe ...

What is causing the click event handler to only function on the initial page?

Within my code for the "fnInitComplete" : function(oSettings, json), I am utilizing a selector like $('[id^=f_]').each(function (). The data for Datatables is retrieved server-side and "bProcessing":true I am aware that my selectors are only ef ...

Error message: The Liferay JavaScript Function has not been defined

I am a newcomer to Liferay and have been attempting to utilize Ajax within my scripts, but unfortunately, the code does not seem to load correctly in the browser. I even tried testing it by simply adding an alert. Every time I try, I encounter the "functi ...

Display the spinner until the data is successfully updated in the DOM using Angular

Dealing with a large dataset displayed in a table (5000 rows), I am attempting to filter the data using column filters. When applying the filter, I have included a spinner to indicate that the filtering operation is in progress. However, due to the quick ...

Add an asterisk before each line of comment when working in a TypeScript file using the VS Code IDE

Within my VS Code workspace, I am using the Typescript language and would like to format my comments across multiple lines with a specific style (look out for the star character) /** *@desc any text * any text */ However, when I attempt to write a comm ...

What is the reason behind Angular not allowing users to define @Output events that begin with 'on'?

While developing a component, I defined an output EventEmitter named onUploaded. However, Angular flagged an error instructing me to use (uploaded) instead. This restriction is due to security concerns, as bindings starting with 'ono' pose risks. ...

Who is the father of Bootstrap Popover?

I'm currently facing an issue with getting a popover to be placed within a specific element. As of now, the popover is being inserted directly into the <body>, but I require it to be relative to other elements. I have been unable to locate a met ...

The screen-responsive navigation bar is experiencing functionality issues

I am facing an issue with my navigation bar on both desktop and mobile. When I maximize the window while the mobile navbar is open, it disappears as expected but the desktop navbar does not appear. I am using a bootstrap template and I am unsure if solving ...

Angular 2: Emptying input field value on click event

I am experiencing an issue with resetting my input values. I have a search bar with filter functions. When I enter a value, it displays a list below and I want to add a function to these links. When I click on one of them, it takes me to another component ...

Animating toggles with JQuery

I am attempting to create a toggle effect for my div using this jQuery script: $(document).ready(function(){ $("button").click(function(){ $("div").animate({left:'250px'}; }, function() { $("div").animate({left:'0px'}; }, }); ...

What is the method for bringing in Mongoose to utilize json.parse()?

I'm really eager to utilize this code for importing a JSON file into JavaScript var treeData; var oReq = new XMLHttpRequest(); oReq.onload = reqListener; oReq.open("get", "test.json", true); oReq.send(); function reqListener(e) { treeData = JSON. ...

Unable to launch React Native project on emulator now

Something seems off with my App as it won't start up on my AS Emulator. Everything was running smoothly yesterday, but today it's not working - possibly due to me moving the npm and npm-cache folders, although they are configured correctly with n ...

Issues with Ajax functionality in Rails

I believe my lack of knowledge in Ajax might be the reason for this issue. My goal is to continuously make ajax calls to my server as I am creating a demo app for learning purposes. Below is the code snippet: Code from job_status/index.html.erb file &l ...

What is the best way to ensure PyScript is completely initialized, including the environment?

Hey there! I'm hoping to catch a specific message being logged in my browser's console by a script I added to my HTML file, and then trigger a JavaScript action based on that. For instance, when "ABCD:READY" appears in the console, I want to cal ...

How can you efficiently pass multiple JSON files as arguments for Observable Arrays, especially when the values from one file are required for use in another file?

My goal is to utilize $.getJSON to retrieve data from two JSON files and assign their values to observableArrays. Currently, I have hard-coded the JSON data into the observableArray. You can view an example on this JSFiddle link. This was my initial appro ...

Tips for selecting multiple elements with the same class name in Protractor for Angular:1. Use the `element

Snippet of HTML code: <div class="block ng-scope" ng-repeat="skills in data.primary_skills"> <div class="block skillsLineItem" ng-class="{manditorySkillsLineItem:skills.mandatory, skillsLineItem:!skills.mandatory}"> < ...

Struggling with developing a chrome extension

I have successfully developed a Chrome extension that, when clicked, says hello world. However, I am facing an issue with creating a simple button that triggers an alert when pressed. Could it be due to the inclusion of JavaScript in an HTML extension file ...

The AJAX request seems to be malfunctioning despite the fact that both the PHP and JS files function correctly independently

I have set up an AJAX call and tested the JS file by alerting out the POST values being sent along with the data string. Everything seems fine at that point. I then passed these values to the PHP file where they are required, making sure to keep it simple ...

Is it better to utilize angular's $interval or a promise to execute code upon completion of an api call?

I am facing an issue with a slow api call in my code. $http.jsonp(url, { params: { 'client': 'translate_about', 'alpha': 1, 'hl': 'en' } }) .success(function (data) { ...

Troubleshooting Problems with CSS `transform` in JQuery UI's `Slide` Transition

While implementing JQueryUI's slide transition on an element with a CSS transform, I encountered an issue where the top half of the element gets hidden during the animation. Is there a way to tweak either my JQueryUI animation or CSS to avoid this pro ...