Why webpack imports all files in subdirectory instead of the right - reactjs

I have React app which render 300 pages. They are divided into 4 groups. There are common settings, custom settings for each group and settings for each page in .json files. I don't want to load all the settings for all pages, but only those needed for a particular page. I try use require to import necessary file:
const getThemeConfig = (theme) => {
const filePath = `./themes/${theme}/config.json`;
return require(`${filePath}`)
};
const themeConfig = getThemeConfig(currentTheme);
this file is imported, but at the same time the application tries to upload absolutely all .json files in ./themes directory. IDK how to fix it.

Related

Is there a way to rename automatically generated routes JSON file in Next.js?

I have a problem, when I click to go to the /analytics page on my site, adblockers block the analytics.json file that's being requested by Next.js as they think it's an analytics tracker (it's not, it's a page listing analytics products).
Is there a way to rename the route files Next.js uses when navigating to server-side rendered pages on the client-side?
I want to either obfuscate the names so they're not machine readable, or have a way to rename them all.
Any help appreciated.
With thanks to #gaston-flores I've managed to get something working.
In my instance /analytics is a dynamic page for a category, so I moved my pages/[category]/index.tsx file to pages/[category]/category.tsx and added the following rewrite:
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: "/:category",
destination: "/:category/category",
},
];
},
};
This now gets the category.json file rather than analytics.json, which passes the adblockers checks and renders as expected.
Note that due to having a dynamic file name in the pages/[category] directory (pages/[category]/[product].tsx), I had to move that to pages/[category]/product/[product].tsx as I was seeing the /analytics page redirected to /analytics/category for some reason without this tweak.

Load GLTF file that is not located in Public folder

I found a problem that I cannot load GLTF files into a scene if I cannot place them in the Public folder in my React application. For example, I have MyPVPanel.gltf, and I want to load it in react app or in my npm library, or I always to be with my react components.
My questions are:
Is this possible to import assets from a specific folder if you develop an npm package. Do packages have something like /public or /assets?
Can I configure my own package to have such a folder with static assets?
How to load GLTF files without a public folder. For example, we can import .png files without problems in react application.
So there is a thing named data URI. You can convert small files in that format(which is basically a base64 encoded string with some metadata at the beginning of it).
data:[<mediatype>][;base64],<data>
In my case [<mediatype>] is data:application/octet-stream.
So if you want to load small file from specific folder in you application, first of all rename your .gltf file into .json. And after importing and converting it into base64 code you can load it using GLTFLoader from three.js library.
Here is a code example:
import myGLTF from './MyPVPanel.json';
import {GLTFLoader} from "three/examples/jsm/loaders/GLTFLoader";
import myGLTF from "./MyPVPanel.json";
const loader = new GLTFLoader();
const stringGLTF = JSON.stringify(myGLTF) // convert Object to a String
const base64EncodedGLTF = btoa(stringGLTF) // Base64 encode the String
//First part is: 'data:application/octet-stream;base64,'
const resultingDataURI = `data:application/octet-stream;base64,${base64EncodedGLTF}`;
loader.load(
resultingDataURI,
(gltf: any) => {
console.log('Loaded!!!');
this.scene.add(gltf.scene)
},
() => {},
(e: any) => console.error(e)
);
}}>Load</button>

Rename JS filles every build in React

Does anyone know how to change the names of the build's generated JS files, without using webpack? ex: every time you have a build change the filenames: 'bundle_v1.js', 'chunk_v2.js' (It doesn't necessarily need to be standardized).
Context: every time we publish our project through Azure, whether in development or production environment, we need to ctrl+f5 to clear the cache and show the changes.
I've already tried to add some configs in the config-overrides.js file but I wasn't successful.
Myconfig-overrides.js:
const {
addBabelPlugin,
override,
} = require('customize-cra');
const path = require('path');
module.exports = override(
addBabelPlugin([
'babel-plugin-root-import',
{
rootPathPrefix: '#/',
rootPathSuffix: 'src',
},
]),
);

Authentication to serve static files on Next.js?

So, I looked for a few authentication options for Next.js that wouldn't require any work on the server side of things. My goal was to block users from entering the website without a password.
I've set up a few tests with NextAuth (after a few other tries) and apparently I can block pages with sessions and cookies, but after a few hours of research I still can't find how I would go about blocking assets (e.g. /image.png from the /public folder) from non-authenticated requests.
Is that even possible without a custom server? Am I missing some core understanding here?
Thanks in advance.
I did stumble upon this problem too. It took my dumbass a while but i figured it out in the end.
As you said - for auth you can just use whatever. Such as NextAuth.
And for file serving: I setup new api endpoint and used NodeJS magic of getting the file and serving it in pipe. It's pretty similar to what you would do in Express. Don't forget to setup proper head info in your response.
Here is little snippet to demonstrate (typescript version):
import { NextApiRequest, NextApiResponse } from 'next'
import {stat} from "fs/promises"
import {createReadStream, existsSync} from "fs"
import path from "path"
import mime from "mime"
//basic nextjs api
export default async function getFile (req: NextApiRequest, res: NextApiResponse) {
// Dont forget to auth first!1!!!
// for this i created folder in root folder (at same level as normal nextjs "public" folder) and the "somefile.png" is in it
const someFilePath = path.resolve('./private/somefile.png');
// if file is not located in specified folder then stop and end with 404
if (! existsSync(someFilePath)) return res.status(404);
// Create read stream from path and now its ready to serve to client
const file = createReadStream(path.resolve('./private/somefile.png'))
// set cache so its proper cached. not necessary
// 'private' part means that it should be cached by an invidual(= is intended for single user) and not by single cache. More about in https://stackoverflow.com/questions/12908766/what-is-cache-control-private#answer-49637255
res.setHeader('Cache-Control', `private, max-age=5000`);
// set size header so browser knows how large the file really is
// im using native fs/promise#stat here since theres nothing special about it. no need to be using external pckages
const stats = await stat(someFilePath);
res.setHeader('Content-Length', stats.size);
// set mime type. in case a browser cant really determine what file its gettin
// you can get mime type by lot if varieties of methods but this working so yay
const mimetype = mime.getType(someFilePath);
res.setHeader('Content-type', mimetype);
// Pipe it to the client - with "res" that has been given
file.pipe(res);
}
Cheers

Location of static application settings

I'm developing a Redux/ReactJS application and I have a list of application settings.
I'm trying to decide if I should have them in the store or if I should create a file which contains the settings and import it where I need it.
It depends on the nature of the 'application settings'.
For the secure things
Like API keys, etc. Use environment variables. You can use something like dotenv to make simulating other environments easier.
For constants
Like strings and colors and external URLs, I use a constants file with multiple exports. Then in each module I import whatever I need, like so:
import {
ANIMATION_DURATION,
COLORS,
MODALS,
TEXT_PADDING,
} from '../../constants.js';
For environment-specific things (e.g. dev, prod ...)
For example API URLs or log levels, etc. use a set of config files. So you might have a config-dev.js and config-prod.js and then a config.js that returns the correct file's contents based on process.env.NODE_ENV
Application settings should be just a const in some file. In this way, for different configurations, the settings can be toggled.
An example of settings file could be:
let apiUrl = 'http://prodUrl';
// __DEV__ defaults to true in simulator.
if (__DEV__) {
apiUrl = 'http://devUrl';
}
export const settings = {
apiUrl,
registerUrl: `${apiUrl}/api/register`,
educationUrl: `${apiUrl}/api/education`,
};

Resources