Vite: Configure webpack-dev-server like functionality in Vite - webpack-dev-server

In webpack I could do something like to this to handle some development middleware code, which includes doing some work/testing inside the app.get call.
devServer: {
before: function (app, server) {
app.get ("/", function (req, resp, next) {
// Do some stuff
resp.redirect ("someUrl")
}
}
}
It seems like Vite should have some kind of similar functionality, but I have not found the right docs yet to help me out. Does anyone have an example of this for Vite?

Related

After deployment getting 404 error axios post

Currently, I'm trying to get axios data from node.js. and i can get the result on local url , however after i build it and deploy it, the post method get 404 error. so i tried to use get method to test it. it gets react html result .
it's totally okay when i do it on local. but only it doesn't work when i build and deployment.
I assumed it's because proxy problem so i installed http-proxy-middleware library and
I try to set up setupProxy.js on my react folder.
this is the example from
"https://create-react-app.dev/docs/proxying-api-requests-in-development/"
but it still doesn't work.
i want to know what can make this issue.
//node.js
app.get("/test", (req, res) => {
res.send({ hello: "Hello world" });
});
const __dirname = path.resolve();
app.use(express.static(path.join(__dirname, "dist")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "dist", "index.html"));
});
//react
const getTest = () => {
axios
.get(`${backend}/test`)
.then(res => {
console.log(res.data);
})
.catch(err => console.log(err));
};
The proxy configuration only applies to the webpack-dev-server you use when developing your React app...
Keep in mind that proxy only has effect in development (with npm start), and it is up to you to ensure that URLs like /api/todos point to the right thing in production.
I would suggest just using the simpler version by adding this to your package.json
"proxy": "http://localhost:5000",
You should also make sure your Express app is configured to handle API requests in both dev and production modes. To do so, I'd recommend using the same routes as used in the requests from the front-end...
app.get("/api/test", (req, res) => {
res.send({ hello: "Hello world" });
});
// or even better
app.use("/api", myApiRouter);
Now your React app can make requests to /api/test in both development and production modes
axios.get("/api/test").then(({ data }) => console.log(data));
In development mode, the proxy configuration will forward the requests to your Express app.
In production mode, your Express app will be serving the built React app via express.static() so they'll be on the same domain.

How does express serve index.html for React App and how do I modify it?

I'm an express noob here and building a React App with server using express and client using create-react-app.
What I want to do
I want to update the title and meta tag in the index.html.
So browser requests url -> Server gets request and adds the title and tag to the index.html -> return it to the browser.
Listed my code here
...
app.use(bodyParser.json())
app.use(aMiddleware)
app.use("/api/foo", bar)
app.use(express.static('client/build'));
if (process.env.NODE_ENV === 'production') {
const path = require('path');
app.get('/*', (req, res) => {
res.sendFile(path.resolve(__dirname, '../client', 'build', 'index.html'))
})
}
Questions
Code is functioning, but I don't know how to replace the title/tag in the index.html
How do I update/replace index for environment that is not prod?
Fo prod environment, I use path.resolve(__dirname, '../client', 'build', 'index.html'), then where is index.html for dev environment? I see there is an index.html in public folder, is it the one that got rendered for dev environment?
I tried to add this code before app.use(express.static(...))
app.get('/', function(req, res) => {
// maybe replace string in the index.html (though I don't know where is it
// then res.send(...)?
})
but this never got triggered. Why?
Stuck on this for a while, tried many things, any help would be great.
You can use react-helmet for this... Or switch to Nextjs which is server side.
https://www.npmjs.com/package/react-helmet

ngrok does not work with react-router when deep links are explicitly defined

Context: I'm opening up my React dev environment to external hits using a paid version of the tool ngrok -- I am running WebPack 4.0 with a devServer.
I go to my app's main page:
https://my-example-domain.ngrok.io
Loads fine.
I click one of the links on my app's main page, The router works well and I see the content for:
https://my-example-domain.ngrok.io/my-sub-page
However, if I refresh at this point, ngrok gives out a 404:
Cannot GET /my-sub-page
The reason I suspect is that in a SPA, the internal app's URLs are processed by the front end in React-Router and externally, there is no resource called /my-sub-page
Is there a way to force this to work?
The problem is that the local server doesn't know about your spa routes(react-router). To fix this, you have to create a simple server that will serve your static build and have a fallback route that will enable spa-routing.
Example in express.js:
import express from 'express';
import path from 'path';
// ... other imports
const app = express();
app.use(express.static('build'));
/*
... some route handlers
*/
// * Unknown endpoint
app.use("/*", (_req, res) => {
res.sendFile(path.join(__dirname, "../build/index.html"), (err) => {
if (err) {
res.status(500).send(err);
}
});
});
app.listen(process.env.PORT || 3000 , ()=>{
console.log('server running')
})
This resolved it -- in webpack.config.js
devServer: {
...
...
historyApiFallback: true, // <- inserting this resolved the issue.
}

React CRA with SSR configuration throws 404 when using the resulting html

I have a react application built using CRA with the default configurations. I wanted to make SSR, so I followed an article something similar to this https://www.vairix.com/tech-blog/server-side-rendering-ssr-of-create-react-app-cra-app-in-2020
Next, I wanted to inline the JS and CSS so that I could hit the URL and copy the resultant HTML page and then use it where ever I want.
For that, I used react-app-rewired plugin which works now I can see the HTML with inline CSS and JS.
The issue is when I copy the generated HTML and save it as .html, and when I open the page, it returns 404 error.
I am trying to copy the HTML that is produced and then use them as individual components in a completely different application.
Am I missing something?
config-overrides.js for react app rewired
const HtmlWebpackPlugin = require("html-webpack-plugin");
const InlineChunkHtmlPlugin = require("react-dev-utils/InlineChunkHtmlPlugin");
const HTMLInlineCSSWebpackPlugin = require("html-inline-css-webpack-plugin").default;
module.exports = {
webpack: function(config, env) {
if (env === "production") {
config.plugins.push(new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/.*/]));
config.plugins.push(new HTMLInlineCSSWebpackPlugin());
}
return config;
}
};
server.js for SSR
import express from "express";
import path from "path";
import renderer from "./react-renderer";
const app = express();
const PORT = 8000;
const routes = ["/custom1/:id","/custom2/:id","/custom3/:id"];
app.get("/*", renderer(routes));
app.use(express.static(path.resolve(__dirname, "../build")));
app.use(express.static(path.resolve(__dirname, "../public")));
app.listen(PORT, () => {
console.log(`App running in the port ${PORT}`);
});
404 is the HTTP code for not found: I don't think the problem is in opening the page but in finding it.
It seems the first route you added in your server is catching all the requests:
app.get("/*", renderer(routes));
you could try moving it as last route
app.use(express.static(path.resolve(__dirname, "../build")));
app.use(express.static(path.resolve(__dirname, "../public")));
app.get("/*", renderer(routes));
More than this you didn't said where you copied the resulting page, I hope in ../build or in ../public directories, otherwise I'm not surprised you can't GET it.

require.ensure error in React Code Splitting

I'm using react-router's code splitting(Dynamic Routing). When building app from webpack it doesn't give error, but when running it, it is giving me error of require.ensure is not a function. I'm using server-side rendering also.
Following is my getComponent code
module.exports = {
path: "/",
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('./component/Home'));
})
}
};
I think server side render doesn't support require.ensure, because node has its own require, and when you use server side render, it will use node require, not webpack require.
I think you should try to user different routes for server and client. the server routes don't use dynamic route

Resources