Trigger a React build fail error if environment variable is missing - reactjs

Is there any way to fail the yarn build step in case any environment variable is missing. In the bitbucket pipeline script the build process is executing even if no env variable is set under the repository variables.

Yes, this can be possible using an approach in the React app. In the root directory create a JS file named as validate-env.js and add the below content in it (I'm using only these env variables in my app - change them according to yours)
require('dotenv').config();
if (!process.env.REACT_APP_WEB_SOCKET_URL) {
throw 'REACT_APP_WEB_SOCKET_URL undefined';
} else if (!process.env.REACT_APP_API_URL_PROD) {
throw 'REACT_APP_API_URL_PROD undefined';
} else if (!process.env.REACT_APP_NODE_ENV) {
throw 'REACT_APP_NODE_ENV undefined';
} else if (!process.env.REACT_APP_CATE_APP) {
throw 'REACT_APP_CATERING_APP undefined';
} else if (!process.env.REACT_APP_FRESH_CHAT_TOKEN) {
throw 'REACT_APP_FRESH_CHAT_TOKEN undefined';
} else if (!process.env.REACT_APP_SENTRY_DSN_KEY) {
throw 'REACT_APP_SENTRY_DSN_KEY undefined';
} else {
console.log('required env set');
}
Make sure to install a dev dependency as yarn add dotenv -D
Now under the package.json file > script section add this line
"validate-env": "node ./validate-env",
and update the build script as (if you are using craco)
"build": "yarn validate-env && craco build",
So, whenever you will run yarn build. It will first check if all the env are present. IF anyone is missing it will fail the build process.

Related

How to resolve env variable at compile time in create-react-app?

I have this simple react code here which uses an environment variable process.env.GREET
<Calculate whatisthis={process.env.GREET} />
In the resulting bundle, I see a reference to process.env.
return /*#__PURE__*/React.createElement(Calculate, {
whatisthis: process && process.env && process.env.GREET || undefined
});
How can I make the bundler put the value of process.env.GREET into the resulting bundle, like so?
return /*#__PURE__*/React.createElement(Calculate, {
whatisthis: 'Hello'
});
This is a pre react-scripts create-react-app.

Using react-pdf with Parcel 2 the "right" way

So I've just upgraded my project to Parcel 2 and I encountered some issues with react-pdf (https://github.com/wojtekmaj/react-pdf) which I've fixed. My question is actually what's the "right" way to have done.
So what I did was the following...
In entry.parcel.js I changed from:
if (typeof window !== 'undefined' && 'Worker' in window) {
pdfjs.GlobalWorkerOptions.workerPort = new Worker('./pdf.worker.entry.js');
}
to Parcel 2's new Worker syntax
if (typeof window !== 'undefined' && 'Worker' in window) {
pdfjs.GlobalWorkerOptions.workerPort = new Worker(
new URL('./pdf.worker.entry.js', import.meta.url),
{ type: 'module' },
);
}
For the moment that change is in my own fork of react-pdf which I pull in via tarball from github.
Additionally certain imports expected that the /dist folder in ./node_modules/react-pdf would exist and it didn't. I added a script in my package.json:
"react-pdf-build": "cd ./node_modules/react-pdf && yarn && yarn build && cd ../../"
and added it to my yarn build command.
So my question remains: is the the "right" way to have done this? if not, please advise what is. Thanks so much!

typescript relay reactjs IRTransformer: Unknown kind `undefined`. using hasura

Hi i got this error which i got before, but i forgot how i solved it.
I created a new query for Relay but I get this error. I remember it has to do something with Typescript, but not sure what i did wrong.
ERROR:
IRTransformer: Unknown kind `undefined`.
error Command failed with exit code 100.
It is not pointing to a particular place in my code, so not sure which code snippet i should include...
this is the query (but it could easily be another one):
const getEvent = `query CreateEventQuery {
eetschema_event_connection(where: {group_id: {_eq: "17ee3ff5-eae1-4482-9ad6-d791a46a9799"}}) {
edges {
node {
name
}
}
}
}
`;
script I run is yarn relay and the problem is at the yarn-compile step
"export-schema": "get-graphql-schema https://XXXX.hasura.app/v1beta1/relay -h 'x-hasura-admin-secret=XXXXX' > ./schema.graphql",
"relay-compile": "relay-compiler --src=./src --schema=./schema.graphql --language typescript ",
"relay": "npm run export-schema && npm run relay-compile",
Somehow reinstalling the relay compiler worked for me.
yarn add relay-compiler-language-typescript

How can I disable chunk(code splitting) with webpack4?

I created react project with : yarn create react-app. I'm using webpack 4.29.6, react 16.8.6.
I want to disable code splitting because I want just one 'main.js' file in build/static/js folder. (I already removed hash from their names.)
I tried:
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
}),
and
splitChunks: {
chunks: 'all',
name: false,
cacheGroups: {
default:false
}
}
but these solutions give me these files:
build
/static
/js
-2.chunk.js
-2.chunk.js.map
-main.chunk.js
-main.chunk.js.map
-runtime~main.js
-runtime~main.js.map
I think runtime~main.js file and .map file are just okay, but I want the exact 'main.js' file without chunk, without 2.chunk.js. How can I disable default code splitting of webpack 4?
plugins: [
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
})
]
Try if this works. Install this manually LimitChunkCountPlugin
https://webpack.js.org/plugins/limit-chunk-count-plugin/
If you created your project with create-react-app and haven't yet ejected, it appears you have two options currently available:
Option 1 - Create a custom build script
First, install the package rewire as a dependency:
npm install rewire
Create a scripts folder, inside create a new file and give it a name e.g., build-non-split.js, then add:
const rewire = require('rewire');
const defaults = rewire('react-scripts/scripts/build.js');
let config = defaults.__get__('config');
config.optimization.splitChunks = {
cacheGroups: {
default: false,
},
};
config.optimization.runtimeChunk = false;
Modify package.json, inside "scripts" and replace build with:
"build": "node ./scripts/build-non-split.js",
Finally, run npm run build or yarn build
Option 2 - Install the package react-app-rewire-disable-chunks
Note: If you go with this option, don't forget to replace the build script with react-app-rewired. Like this:
"build": "react-app-rewired build",
Source: Disabling code splitting in CRA2 #5306

Typescript including different files depending on compilation command

I used creat-react-app to initialize some code which I want to share between native and web. In my package.json I have two separate commands for starting for each platform using react-scripts-ts and react-native-scripts-ts:
package.json
...,
"scripts": {
"tsc": "tsc",
"clean": "rimraf artifacts",
"build": "npm run clean && npm run tsc --",
"start-web": "npm run build && react-scripts-ts start",
"start-native": "npm run build && react-native-scripts start",
},
...
(a detailed description on how to do this can be found here https://medium.com/#yannickdot/write-once-run-anywhere-with-create-react-native-app-and-react-native-web-ad40db63eed0)
This great and I can use react-native components on both platforms. The problem I have is when I try to use external packages such as react-routing.
I include both react-router-native and react-router-dom in my package.json. I am trying to achieve what is described in this article (https://medium.com/#yannickdot/hi-jared-2650fbb2eda1) but using typescript not JS, giving me:
routing.native.tsx
export {
NativeRouter as Router, // Rename
Switch,
Route,
Link
} from 'react-router-native'
routing.web.tsx
export {
BrowserRouter as Router,
Switch,
Route,
Link
} from 'react-router-dom'
However, contrary as described in the article, when using typescript, it is not automatically recognized which file should be included. I get the simple error:
src/App.tsx:10:26 - error TS2307: Cannot find module './routing'.
10 import Router from "./routing";
Which makes sense because when I look at the output of the compiler, no module routing exists:
artifacts
| App.js
| routing
| routing.native.js
| routing.web.js
How can I tell the typescript compiler to include all *.native.tsx files when running the start-native command and all *.web.tsx files when running the start-web commmand?
Ideally, this should be possible at compile-time, passing additional parameters into the typescript compiler, which override the tsconfig.json. Example:
tsc --exclude="./**/*.native.tsx"
I know this can be done with a hacked solution, e.g. by writing a script to copy the entire source, deleting all unwanted files, keeping the correct ones, and compiling that copied source folder, but I want to know if there is a more neat way to do this.
Thanks in advance!
A possible solution without using external tools :
1. Create a function to check the platform running
see this question on Stackoverflow
export default function getPlatform(): string {
if (typeof document != 'undefined') {
// I'm on the web!
return 'web';
}
else if (typeof navigator != 'undefined' && navigator.product == 'ReactNative') {
// I'm in react-native
return 'native';
}
else {
// I'm in node js
return 'node';
}
}
2. Create routing/index.ts
import getPlatfrom from '../getPlatform';
const platform = getPlatfrom();
const routing = platform === 'web' ? require('./routing.web') : require('./routing.native');
export const {Router, Switch, Route, Link} = routing;
3. Use the routing
import { Route } from './routing/index';
You may add an interface IRouting and some type casting in routing/index, so that you don't lose type safety and autocompletion ...

Resources