Hot reloading React + Redux + SSR with Webpack, how to do it? - reactjs

I'm trying to implement hot reloading in my company's project. The projet works with React, Redux and .NET with Serverside Rendereing (SSR). I want my project to hot reload when I'm working on my React and SCSS files and keep my state as is (so I don't have to redo the clicks etc. on my app).
To achieve that, I tried to use the devServer conf from Webpack, like so :
devServer: {
static: distFolder,
devMiddleware: {
writeToDisk: true,
serverSideRender: true,
publicPath: distFolder
},
proxy: {
context: () => true,
target: 'http://localhost:5000',
},
hot: true,
port: 3000
},
The webpack dev server is running well, but I have an error on my app :
Error
Note that I tried several options, with or without proxy, with or without serverSideRender, with or without static... I can't find any way to solve this on the webpack documentation, so I'm looking for people who had the same issues and who managed to resolve it.
Thanks !

Related

Vite pwa plugin not working in development environment for react apps

I'v already migrated from webpack to vite and used vite pwa plugin to register a service worker.
My problem is that when I try to use a custom path for service worker, Vite will work fine in production, but in development cause 404 error.
here is my VitePwa vite.config.js:
VitePWA({
srcDir: 'src',
filename: 'sw.js',
devOptions: {
enabled: true,
},
strategies: 'injectManifest',
injectManifest: {
injectionPoint: undefined
}
}),
I already got that, in the development environment, vite pwa plugin is looking for sw.js in the public directory but I want it to get it from src
I got the solution
First, setting type as module is needed in vitePwaPlugin config in devOptions:
devOptions: {
enabled: true,
type: 'module',
},
and vitePwaPlugin will try to install dev-sw.js?dev-sw file as service worker
Second, for handling registeration I used registerSW from virtual:pwa-register
import { registerSW } from 'virtual:pwa-register';
if ('serviceWorker' in navigator) {
registerSW();
}

webpack-dev-server - Remove URI fragment from URL when live reloading

I'm dealing with an Angular 1 application that uses URI fragments for routing purposes.
For example:
http://localhost:3000/#/home
http://localhost:3000/#/menu
http://localhost:3000/#/list
Rather than:
http://localhost:3000/home
http://localhost:3000/menu
http://localhost:3000/list
When I'm using Webpack Dev Server to launch a local server with hot reloading, every time I apply some changes, Webpack reloads the URL but keeping the "/#/route" part.
Unfortunately, due to some code restrictions, I need to always reload the page from "/" because some redirections are applied internally when the app launches the first time and the app will crash if you try to start directly from any URI fragment.
I tried to use the "proxy" and "historyApiFallback" configurations in webpack.config.js like:
devServer: {
proxy: {
'/#': {
target: 'http://localhost:3000',
pathRewrite: { '^/#': '' }
}
}
And:
devServer: {
historyApiFallback: {
verbose: true,
rewrites: [{ from: /^\/#/, to: '/' }]
}
}
But so far, I didn't have any luck. The URL keeps the hash when reloading.
Any suggestions or ideas to configure Webpack Dev Server to always start from "/" and remove the hash URI?

How to proxy request in Docusaurus v2?

I'm trying to config my Docusaurus web app to proxy the request to my api endpoint. For example, if I make a fetch request in my app fetch(/api/test), it will proxy the request from localhost:3000/api/test to my {{api_endpoint}}/api/test, but I'm still struggling to do it.
What I've done:
add a proxy field in package.json
create a setupProxy.js in the src folder
These 2 are based on the Proxying API Requests in Development
Another approach way is I created a custom webpack plugin and add it to the Docusaurus config
Does anyone have experience on this problem ? Thanks for reading, I really appreciate your help.
I went down the exact same path. Ultimately Docusaurus runs its Webpack dev server under the hood which is why the proxy field and setupProxy.js were not working as expected. I was able to get the outside API call by proxy and solved CORS errors by creating a Docusaurs plugin like you are attempting. Adding the "mergeStrategy" and "changeOrigin" were the keys to getting it all working.
// plugins/webpack/index.js
module.exports = function (context, options) {
return {
name: "cusotm-webpack-plugin",
configureWebpack(config, isServer, utils) {
return {
mergeStrategy: { "devServer.proxy": "replace" },
devServer: {
proxy: {
"/YOUR_COOL_ROUTE": {
target: "https://YOUR_COOL_API/",
secure: false,
changeOrigin: true,
logLevel: "debug",
},
},
},
};
},
};
};

Matching root route in webpack-dev-server's historyApiFallback`

Sample repo demonstrating the issue is here.
I'm trying to set up webpack dev server so that:
Requests to / are served by public/landing.html (a static landing page)
Requests to anything else are served by my React app
Using create-react-app, and based on webpack-dev-server's options, I've set up my webpackDevServer.config.js as follows:
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebookincubator/create-react-app/issues/387.
disableDotRule: true,
rewrites: [
// shows views/landing.html as the landing page
{ from: /^\/$/, to: 'landing.html' },
// shows views/subpage.html for all routes starting with /subpage
{ from: /^\/subpage/, to: 'subpage.html' },
// shows views/404.html on all other pages
{ from: /./, to: '404.html' },
],
},
And when I start webpack here's what I see:
Requests to /subpage are routed correctly to subpage.html
Requests to /foo are routed correctly to 404.html. Eventually, these would be handled by my React app.
Requests to / are routed incorrectly to my React app.
How can I get landing.html to respond to requests at /?
I ended up opening a bug request with webpack-dev-middleware and discovered it was not a bug but a failure of configuration.
Specifically, the issue is using HtmlWebpackPlugin alongside historyApiFallback. I believe plugins are processed before the regex matching, and HtmlWebpackPlugin's default file output is index.html; this means that out of the box, / will always be routed to the HtmlWebpackPlugin output file.
The solution to this is to set a custom filename in HtmlWebpackPlugin, which allows you to control the matching again. Here's a sample repo demonstrating the fix and here's the webpack config:
module.exports = {
context: __dirname,
entry: [
'./app.js',
],
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
devServer: {
publicPath: "/",
// contentBase: "./public",
// hot: true,
historyApiFallback: {
// disableDotRule: true,
rewrites: [
{ from: /^\/$/, to: '/public/index.html' },
{ from: /^\/foo/, to: '/public/foo.html' },
{ from: /(.*)/, to: '/test.html' },
],
}
},
plugins: [
new HtmlWebpackPlugin({
title: "Html Webpack html",
hash: true,
filename: 'test.html',
template: 'public/plugin.html',
}),
],
};
Two thoughts come to mind:
What you want to do is not possible with Webpack Dev Server (as far as I'm aware)
And, once npm run build is run and deployed the deployed app would not follow the same rules as configured in Webpack Dev Server
Even if I'm mistaken on #1, #2 seems like a bigger issue if you ever plan to deploy the app. This leads me to recommend an alternate setup which will work on dev and production (or wherever it's deployed).
A few options:
setup the app as a single-page app (SPA) and use React Router to serve the static routes (/ and /subpage) and wildcards (everything else)
setup node (or another server) to serve the static routes (/ and /subpage) and wildcards (everything else)
An Attempt
In an attempt to setup the routes I was able to achieve this setup:
Display landing.html when / is requested
Display subpage.html when /subpage is requested
Display the React App at a specific path, like app.html
To do this make the following changes:
Move /public/index.html to /public/app.html
mv ./public/index.html ./public/app.html
In /config/webpackDevServer.config.js, update historyApiFallback to:
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebookincubator/create-react-app/issues/387.
disableDotRule: true,
rewrites: [
// shows views/landing.html as the landing page
{ from: /^\/$/, to: "landing.html" },
// shows views/subpage.html for all routes starting with /subpage
{ from: /^\/subpage/, to: "subpage.html" },
// shows views/app.html on all other pages
// but doesn't work for routes other than app.html
{ from: /./, to: "app.html" }
]
}
In /config/paths.js update appHTML to:
appHtml: resolveApp("public/app.html")
In /config/webpack.config.dev.js, updateplugins` to include:
new HtmlWebpackPlugin({
filename: "app.html",
inject: true,
template: paths.appHtml
})
Requesting a random URL, like localhost:3000/foo will return a blank page but contains the HTML from the app.html page without the bundled <script> tags injected. So maybe you can find a solution to this final hurdle.

Webpack - React ES6 transpile every template (src to dist)

I am using webpack for react(es6) project.
My problem
I have built react app with ES6, so everywhere i have used import keyword for dependency. Now for server side rendering i am using NodeJS so its not support import yet. For this i have to use require instead of import.
Now i have used webpack for bundling my app, but it always generate final bundle file (single.bundle.js), That's why i am not able to import chunk of transpiled code for server side rendering.
Solution
If it is possible to transpile every file (src to dist), then i can import this es5 file into nodejs server code.
Question
Is this possible with webpack to transpile whole folder with same out put rather than bundle file ?
Otherwise i have to use grunt or gulp. :(
You can use webpack for server too. It will transpile to webpack server bundle only your specific code containing react and excluding node_modules by externals option. Here is example of webpack.config.js for server side
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
module.exports = {
entry: './src/server.js',
output: {
path: __dirname,
filename: 'server.js'
},
target: 'node',
node: {
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false,
},
externals: nodeModules,
}

Resources