How to set file's default suffix in webpack-dev-server? - webpack-dev-server

I use webpack-dev-server to server my project.Here is the question, When the browser send a request like http://localhost:9000/test/menuList, acutally I want it to find http://localhost:9000/test/menuList.json. How should I do?

You can try tweaking Webpack-dev-server proxy object pathRewrite property
devServer: {
contentBase: <Your-Value>,
proxy = {
'/test/menuList': {
target: http://localhost:9000/test/menuList,
pathRewrite(req, options) {
return req + '.json';
}
}
}
...
}

Related

Vite serving shader file with wrong (none) MIME type

I'm developing a BabylonJS application. BabylonJS PostProcess class appends .fragment.fx to a given file name and requests that from the server. When my local Vite (version 4.0.4) dev server serves this file the content-type header is empty. This causes Firefox to intepret it as type xml and fail. Chrome fails through a different, but I think related, mechanism.
How do you configure Vite to serve the *.fragment.fx static files as text/plain? I assume I need to disable the default middleware and write some custom code instead, like this: https://vitejs.dev/config/server-options.html#server-middlewaremode but I wanted to first check there wasn't something else going on / a simpler way to configure / fix this.
The vite dev server is started using vite --host --port 3000 --force and the config in vite.config.js is:
import { defineConfig } from 'vite';
export default defineConfig(({ command, mode }) => {
// if (command === 'serve') {
// return {
// // dev specific config
// }
// } else {
// // command === 'build'
// return {
// // build specific config
// }
// }
return {
resolve: {
alias: {
"babylonjs": mode === "development" ? "babylonjs/babylon.max" : "babylonjs",
}
},
base: "",
// assetsInclude: ['**/*.fx'],
};
});
* edit 1 *
I have seen there's a parameter ?raw that can be added to the URL however I don't control how BabylonJS forms the URL so I can't see how to make this work in this situation.
I followed these instructions and set up a dev server using express. I added this block of code above the call to app.use(vite.middlewares):
app.use("**/*.*.fx", async (req, res, next) => {
const url = req.originalUrl
const file_path = path.resolve(__dirname, "." + url)
const file = fs.readFileSync(file_path, "utf-8")
res.status(200).set({ "Content-Type": "text/plain" }).end(file)
})
I now start the dev server using the following script line in the package.json of "dev": "node server",
I could not find a way to solve this by configuring the default vite dev server.

Webpack obfuscator not working with craco, maps disabled

today I have a very large problem using react & craco, I can't seem to get my webpack-obfuscator to do anything. I have disabled source maps, but to no avail.
This is my craco config:
const path = require("path");
const WebpackObfuscator = require('webpack-obfuscator');
module.exports = {
webpack: {
configure: (webpackConfig) => {
// Because CEF has issues with loading source maps properly atm,
// lets use the best we can get in line with `eval-source-map`
if (webpackConfig.mode === 'development' && process.env.IN_GAME_DEV) {
webpackConfig.devtool = 'eval-source-map'
webpackConfig.output.path = path.join(__dirname, 'build')
}
return webpackConfig
},
plugins: {
add: [
new WebpackObfuscator ({
rotateStringArray: true
}),
],
},
},
devServer: (devServerConfig) => {
if (process.env.IN_GAME_DEV) {
// Used for in-game dev mode
devServerConfig.writeToDisk = true
}
return devServerConfig
}
}
I get no visible maps files when building, and I've put "GENERATE_SOURCEMAP=false" in my .env file that's located where the package.json is.
Hopefully someone has the answer as to why this is happening.
Kind regards, and thanks for reading.
To upgrade a short config, you can use a construct that, if the condition is met, updates the configuration without using WebpackObfuscator:
module.exports = {
webpack: {
configure: {
...(process.env.IN_GAME_DEV && process.env.NODE_ENV === 'development' && {devtool: 'eval-source-map'})
}
}
}
Also, if you need additional properties for the configuration, in addition to the dvttool, you can add them

webpack-dev-server set cookie via proxy

We have setup our development environment with webpack-dev-server. We use its proxy config to communicate with the backend.
We have a common login page in the server which we use in all our applications. We it is called, it sets a session cookie which expected to passed with subsequent requests. We have used the following config but the cookie is not set in the browser for some reason. I can see it in response header in the network tab of dev tool.
const config = {
devServer: {
index: "/",
proxy: {
"/rest_end_point/page": {
target: "https://middleware_server",
secure : false
},
"/": {
target: "https://middleware_server/app/login",
secure : false
},
}
The https://middleware_server/app/login endpoint returns the login page with the set-cookie header.
The proxy is used to avoid CORS errors when accessing login pages and API calls.
Upto this point no code from the application is executed. Do we have to do something in the coomon login page to get the cookie set?
the application is written with React.
Any help would be appreciated.
I have the same use case and this is what I have done.
In my case, I have multiple proxy targets so I have configured the JSON (ProxySession.json) accordingly.
Note: This approach is not dynamic. you need to get JSESSIONID manually(session ID) for the proxy the request.
login into an application where you want your application to proxy.
Get the JSESSIONID and add it in JSON file or replace directly in onProxyReq function and then run your dev server.
Example:
Webpack-dev.js
// Webpack-dev.js
const ProxySession = require("./ProxySession");
config = {
output: {..........},
plugins: [.......],
resolve: {......},
module: {
rules: [......]
},
devServer: {
port: 8088,
host: "0.0.0.0",
disableHostCheck: true,
proxy: {
"/service/**": {
target: ProxySession.proxyTarget,
changeOrigin: true,
onProxyReq: function(proxyReq) {
proxyReq.setHeader("Cookie", "JSESSIONID=" + ProxySession[buildType].JSESSIONID + ";msa=" + ProxySession[buildType].msa + ";msa_rmc=" + ProxySession[buildType].msa_rmc + ";msa_rmc_disabled=" + ProxySession[buildType].msa_rmc);
}
},
"/j_spring_security_check": {
target: ProxySession.proxyTarget,
changeOrigin: true
},
"/app_service/websock/**": {
target: ProxySession.proxyTarget,
changeOrigin: true,
onProxyReq: function(proxyReq) {
proxyReq.setHeader("Cookie", "JSESSIONID=" + ProxySession[buildType].JSESSIONID + ";msa=" + ProxySession[buildType].msa + ";msa_rmc=" + ProxySession[buildType].msa_rmc + ";msa_rmc_disabled=" + ProxySession[buildType].msa_rmc);
}
}
}
}
ProxySession.json
//ProxySession.json
{
"proxyTarget": "https://t.novare.me/",
"build-type-1": {
"JSESSIONID": "....",
"msa": "....",
"msa_rmc": ...."
},
"build-type-2": {
"JSESSIONID": ".....",
"msa": ".....",
"msa_rmc":"....."
}
}
I met the exact same issue, and fixed it by this way:
This is verified and worked, but it's not dynamic.
proxy: {
'/my-bff': {
target: 'https://my.domain.com/my-bff',
changeOrigin: true,
pathRewrite: { '^/my-bff': '' },
withCredentials: true,
headers: { Cookie: 'myToken=jx42NAQSFRwXJjyQLoax_sw7h1SdYGXog-gZL9bjFU7' },
},
},
To make it dynamic way, you should proxy to the login target, and append a onProxyRes to relay the cookies, something like: (not verified yet)
onProxyRes: (proxyRes: any, req: any, res: any) => {
Object.keys(proxyRes.headers).forEach(key => {
res.append(key, proxyRes.headers[key]);
});
},
"/api/**": {
...
cookieDomainRewrite: { "someDomain.com": "localhost" },
withCredentials: true,
...
}
You can use this plugin to securely manage auth cookies for webpack-dev-server:
A typical workflow would be:
Configure a proxy to the production service
Login on the production site, copy authenticated cookies to the local dev server
The plugin automatically saves your cookie to system keychain
https://github.com/chimurai/http-proxy-middleware#http-proxy-options
use option.cookieDomainRewrite and option.cookiePathRewrite now
cookies ??
devServer: {
https: true, < ------------ on cookies
host: "127.0.0.1",
port: 9090,
proxy: {
"/s": {
target: "https://xx < --- https
secure: false,
//pathRewrite: { "^/s": "/s" },
changeOrigin: true,
withCredentials: true
}
}
}
. . . . . . . . . . .

Using constant/variable as webpack dev server proxy URL pattern

In our development server setup we use webpack-dev-server proxy setting to connect ot the APIs via middleware server. Time to time we have to change the middleware server settings and without changing the information in multiple places we would like to keep them in a single place.
Therefore we tried the following,
const MIDDLEWARE_SERVER = 'https://midlleware.server';
const MIDDLEWARE_RESOURCE = '/xyz';
const MIDDLEWARE_API_ENDPOINT = MIDDLEWARE_SERVER + MIDDLEWARE_RESOURCE + '/api';
devserver: {
proxy: {
MIDDLEWARE_RESOURCE : {
target: MIDDLEWARE_API_ENDPOINT;
pathRewrite: { MIDDLEWARE_RESOURCE: '' },
}
}
This doesn't work resulting with a 404 error because the URL pattern has not recognised (we checked by catching a onProxyReq event).
But if we replace the MIDDLEWARE_RESOURCE with '/xyz' in the proxy section it works.
it that a limitation in providing 'proxy' patterns?
Thanks
I was able to get it work by using [MIDDLEWARE_RESOURCE] notation. Like below
const MIDDLEWARE_SERVER = 'https://midlleware.server';
const MIDDLEWARE_RESOURCE = '/xyz';
const MIDDLEWARE_API_ENDPOINT = MIDDLEWARE_SERVER + MIDDLEWARE_RESOURCE + '/api';
devserver: {
proxy: {
[MIDDLEWARE_RESOURCE] : {
target: MIDDLEWARE_API_ENDPOINT;
pathRewrite: { MIDDLEWARE_RESOURCE: '' },
}
}

How to proxy with Gatsby and custom Webpack config (netlify-lambda)

I'm using Gatsby with netlify-lambda which creates a server for functions on the 9000 ports:
http://localhost:9000/myFunctionName
In production the address of the functions is:
/.netlify/functions/myFunctionName
So I would like to have a dev mode proxy that serves http://localhost:9000/ when I call /.netlify/functions.
My custom Webpack config in gatsby-node.js:
exports.modifyWebpackConfig = ({ config, stage }) => {
if (stage === 'develop') {
config.merge({
devServer: {
proxy: {
'/.netlify/functions': {
target: 'http://localhost:9000',
pathRewrite: {
'^/\\.netlify/functions': ''
}
}
}
}
})
}
}
Does not work.
I tried this too https://www.gatsbyjs.org/docs/api-proxy/#api-proxy but I need to rewrite the url and not just prefix.
What's the best way to use netlify-lambda with Gatsby ?
Thanks
Update: Gatsby now does support Express middleware, in this merged PR. This will not support the Webpack Dev Server proxy configuration, but will allow using ordinary Express proxy middleware.
To use with netlify-lambda just add this to your gatsby-config.js :
const proxy = require("http-proxy-middleware")
module.exports = {
developMiddleware: app => {
app.use(
"/.netlify/functions/",
proxy({
target: "http://localhost:9000",
pathRewrite: {
"/.netlify/functions/": "",
}
})
)
}
}
https://www.gatsbyjs.org/docs/api-proxy/#advanced-proxying
Unfortunately, the Gatsby development proxy configuration is not at all extensible. Since Gatsby does not use the webpack dev server, its proxy options are not available. See https://github.com/gatsbyjs/gatsby/issues/2869#issuecomment-378935446
I achieve this use case by putting an nginx proxy in front of both my Gatsby development server and the netlify-lambda server. This is a very simplified version of the proxy server config (trailing slash is important):
server {
listen 8001;
location /.netlify/functions {
proxy_pass http://0.0.0.0:9000/;
}
location / {
proxy_pass http://0.0.0.0:8000;
}
}
I'm using an nginx proxy anyhow, so that's not an undesirable amount of extra dev setup, but it would certainly be better if Gatsby supported this common case.

Resources