How can I add dependency in package.json dynamically - reactjs

I have package.json file as follows (locally):
...the rest
"dependencies": {
"my-dependency": "link:../my-dependency-link"
}
...the rest
What I want is that my-dependency be added based on envinroment.
Local I want to link other local project and in production I want to use yarn link:
Thus, package.json should be something as follows:
...the rest
"dependencies": {
"my-dependency": isDev ? "link:../my-dependency-link" : "yarn:some-name"
}
...the rest
I know that I can't do if's inside package.json but is there any other possibility?

Related

Use Environnement variable in package.json with React

Is it possible to use an environnement variable in package.json ?
I got a .env file at the root of my projet with some variables
REACT_APP_DEV_URL='my_url'
REACT_APP_PROD_URL='my_url'
And I would like to use it in my package.json file like this :
{
"proxy": process.env.REACT_APP_DEV_URL
}
It seems that I can't do that. Is there a trick or something missing ?
Thanks

Typescript library import with sub paths

I have a Typescript library that is being consumed from a React app. I wanted to import the TS library contents with sub-paths like
import {base} from "my-lib"
import {foo} from "my-lib/path1"
import {bar} from "my-lib/path2"
I came across the Github issue which states that this is not yet supported (exports in package.json) by Typescript. I'm using Typescript 4.3.
There is a workaround posted in the same thread - Github repo typescript-subpath-exports-workaround. It uses exports and typeVersions
{
"main": "dist/index.js",
"types": "dist-types/index.d.ts",
"exports": {
".": "./dist/index.js",
"./exported": "./dist/exported.js"
},
"typesVersions": {
"*": {
"exported": ["dist-types/exported"]
}
}
}
I created a new react app (via npx create-react-app command) and tried importing hello from typescript-subpath-exports-workaround and it worked fine. But couldn't import `typescript-subpath-exports-workaround/exported
import {hello} from "typescript-subpath-exports-workaround" //works fine
import {foo} from "typescript-subpath-exports-workaround/exported" //gives "Module not found" error
Full error is below:
./src/App.js
Module not found: Can't resolve 'typescript-subpath-exports-workaround/exported' in '/Users/...../my-react-app/src'
Codesandbox code - https://codesandbox.io/s/create-react-app-forked-5yxd8
UPDATE: The sub-path used in import and the folder structure are different. In the above example, there won't be a folder named path1 or path2.
Look at the Next.JS React Framework. You can see that they use exactly the same approach as you have described. You can create a simple typescript application with their CLI tool like this:
npx create-next-app#latest --typescript
Then pay attention on imports used for instance in ./pages/index.tsx.
Then if you'll look into the ./node_modules/next/package.json you will see that they expose built files in two ways: actual code and type defs are inside ./node_modules/next/dist/* and their re-exports are right in ./node_modules/next/*.
At least this is a real-life example and a good place to start your experiments. It doesn't mean you have to learn the whole their codebase. You just need to mimic the essencial parts of their package.json file (https://github.com/vercel/next.js/blob/canary/packages/next/package.json), specifically main, types and files in your Typescript library.
Update
Just look where absent imports could be imported from:
As you might understand, those are the places, where corresponding *.d.ts files are placed. So you just need to create reexport files in the root folder of you library and mention them in 'files' property of your lib's package.json.
The exactly similar picture I have for my own library.
I think there is no other way to impement imports of your lib the way you want, except of having either reexports or original type definitions right in the lib's root folder
This block in my package.json worked for me:
{
// ...
"files": [
"/dist"
],
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": "./dist/index.js",
"./types": "./dist/types/index.js",
"./generate": "./dist/generate/index.js"
},
"typesVersions": {
"*": {
"types": [
"./dist/types/index.d.ts"
],
"generate": [
"./dist/generate/index.d.ts"
]
}
}
}
My tsconfig.json looks like this:
{
"extends": "#tsconfig/node14/tsconfig.json",
"include": ["src/**/*"],
"compilerOptions": {
"lib": ["es2020", "dom"],
"declaration": true,
"outDir": "dist",
"module": "ESNext"
}
}
And this is my file structure:
package.json
tsconfig.json
dist/ // and all its subfolders
src/
generate/
index.ts
types/
index.ts
index.ts
Separately, I'm using TypeScript 4.7.4. Supposedly the exports field is supported with this version, but it didn't work for me. But this (maybe overly complex) workaround worked for me.
As answered in How to create a local module in TypeScript:
Using module-alias package might solve your problem.
Add this configuration below into package.json:
"_moduleAliases": { "my-module":
"<your_build_folder>/modules/my-module" },
And this code on first line
of your main file (server.ts/index.ts)
import 'module-alias/register';

How to configure react-script so that it doesn't override tsconfig.json on 'start'

I'm currently using create-react-app to bootstrap one of my projects. Basically, I'm trying to set up paths in tsconfig.json by adding these to the default tsconfig.json generated by create-react-app:
"baseUrl": "./src",
"paths": {
"interfaces/*": [
"common/interfaces/*",
],
"components/*": [
"common/components/*",
],
},
However, every time I run yarn start which basically runs react-scripts start, it deletes my changes and generates the default configurations again.
How can I tell create-react-app to use my custom configs?
I was able to do this by using advice from this issue.
Put the configuration options react scripts likes to remove in a separate file (e.g. paths.json) and reference it from tsconfig.json via the extends directive.
paths.json:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"interfaces/*": [ "common/interfaces/*"],
"components/*": [ "common/components/*"],
}
}
}
tsconfig.json
{
"extends": "./paths.json"
...rest of tsconfig.json
}
Create React App does not currently support baseUrl. However there is a workaround...to setup baseUrl for both webpack and the IDE you have to do the following:
Create a .env file with the following code:
NODE_PATH=./
Create a tsconfig.paths.json file with the following code inside:
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"src/*": ["*"]
}
}
}
Add the following line to tsconfig.json
{
"extends": "./tsconfig.paths.json",
...
}
You can't and I am unsure when you will be able to. I have been trying to use baseUrl and paths so I can avoid relative imports but as you can see they are intentionally removing certain values. The "(yet)" is encouraging but (sigh) who knows when they will officially be supporting it. I recommend subscribing to this github issue to be alerted if/when this changes.
The following changes are being made to your tsconfig.json file:
- compilerOptions.baseUrl must not be set (absolute imports are not supported (yet))
- compilerOptions.paths must not be set (aliased imports are not supported)
If you are using react-scripts 4.0.0 like me then all you need to do is remove the line (around line 160 on my end):
paths: { value: undefined, reason: 'aliased imports are not supported' }
from the file node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
I was able to straight up add my baseUrl and paths config to my tsconfig.json file like so:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#domain/*": ["../src/domain/*"],
},
}
}
and finally compile and move on with my life.
Per usual, YMMV. Please test your stuff. This is obviously a hack but it worked for me so I'm posting here in case it helps someone.
Here's a patch if you feel like sharing with your team:
diff --git a/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js b/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
index 00139ee..5ccf099 100644
--- a/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
+++ b/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
## -156,7 +156,8 ## function verifyTypeScriptSetup() {
: 'react',
reason: 'to support the new JSX transform in React 17',
},
- paths: { value: undefined, reason: 'aliased imports are not supported' },
+ // Removed this line so I can add paths to my tsconfig file
+ // paths: { value: undefined, reason: 'aliased imports are not supported' },
};
Edit
Per #Bartekus thoughtful suggestion in the comments thread I'm adding information on the package I use when I need to add (possibly) temporary changes like these to an npm package: patch-package
The package essentially provides a way to make changes to a package in a cleaner way. Especially when you consider collaboration it becomes very cumbersome to directly change an npm file and move on. The next time you update that package or even when you start developing in a new machine and run npm install your changes will be lost. Also, if you have teammates working on the same project they would never inherit the changes.
In essence you go through the following steps to patch a package:
# fix a bug in one of your dependencies
vim node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
# run patch-package to create a .patch file
npx patch-package react-scripts
# commit the patch file to share the fix with your team
git add patches/react-scripts+4.0.0.patch
git commit -m "Enable aliased imports in react-scripts"
Next time someone checks out the project and installs it, the patch will be applied automatically due to a post-install script you add during set up:
"scripts": {
+ "postinstall": "patch-package"
}
See up to date instructions in the package's documentation
I had a similar issue to this general problem (CRA overwrites "noEmit": false in my tsconfig.json of a React library I'm working on where I have two separate builds, one for local development, and another to build the production library with typings). Simple solution: use sed in a postbuild script in the package.json. For example: In-place edits with sed on OS X .
{
...
"scripts": {
...
"postbuild": "sed -i '' 's/{THING CRA IS REPLACING}/{WHAT YOU ACTUALLY WANT}/g' tsconfig.json # CRA is too opinionated on this one.",
...
}
...
}
This approach, however, is not cross-platform (unlike how rimraf is the cross-platform alternative to rm -rf).
For me, the problem was with VSCode using an older version of typescript (4.0.3), while the typescript version shipped with the project is (4.1.2).
The following did the trick for me:
Go to the command palette CTRL+Shift+P.
Choose "TypeScript: Select a TypeScript Version...".
Choose "Use workspace Version".
On Botpress (with react-scripts 4.0.3), we use a combination of 2 tricks to use paths without ejecting or patching the code. As Glenn and Microcipcip said, the first step is to extend the tsconfig.json file
tsconfig.path.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"~/*": ["src/*"],
"common/*": ["../bp/src/common/*"]
}
}
}
tsconfig.json
{
...
"extends": "./tsconfig.paths.json"
}
Then to make it work in the background, use the package react-app-rewired. It allows to make slight adjustments to the webpack configuration without actually ejecting CRA.
config-overrides.js
module.exports = {
webpack: (config, env) => {
config.resolve.alias['common'] = path.join(__dirname, '../bp/dist/common')
config.resolve.alias['~'] = path.join(__dirname, './src')
}
}
To see the full code, you can check the github repository https://github.com/botpress/botpress/tree/master/packages/ui-admin
For macOS this workaround should work.
package.json
"scripts": {
"start": "osascript -e 'tell app \"Terminal\" to do script \"cd $PATH_TO_REACT_APP && node ./setNoEmitFalse\"' && react-scripts start",
...
},
...
setNoEmitFalse.js
const fs = require('fs');
const { sleep } = require('sleep')
const path = './tsconfig.json'
const run = async () => {
sleep(2)
const tsconfig = fs.readFileSync(path, 'utf-8');
const fixed = tsconfig.replace('"noEmit": true', '"noEmit": false');
fs.writeFileSync(path, fixed)
}
run()
The execution of the javascript file in a separate terminal (osascript) provides the normal output for react-scripts in the original terminal.
Go to node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js and replace
const compilerOptions = {
...
};
by
const compilerOptions = { };

Is it good to use package.json file in react component file?

I have to use version mentioned in package.json file in front-end(react js) file.
{
"name": "asdfg",
"version": "3.5.2", // want to use this
"description": "description",
"scripts": {}
//etc etc etc
......
}
Send package.json [version] to Angularjs Front end for display purposes
I'd gone through above post and found two ways for the same. but none of them I was asked to implement.
#1. During build process
#2. By creating endpoint
So I want to know the approach below is valid/good or not ?
react-front-end-file.js
import packageJson from '../package.json'; // imported
...
...
// Usage which gives me version - 3.5.2
<div className='app-version'>{packageJson.version}</div>
Let me know if this approach is fine.
The below 2 approaches seems to have either dependency or add an extra implentation which might not be needed
During build process - ( has dependency on module bundler like webpack etc.)
By creating endpoint - ( needs an extra code at server just to get version )
Instead, As package.json is a file which takes json object in it so you can use it to import json and use its any keys mentioned in that file ( version in your case but only constraint here is, you should have access to package.json file after application deployment, so dont forget to move file in deployment environment )
So your approach seems to be fine.
I would do something like this:
In your module bundler, require your package json file and define a global variable and use it wherever you want
e.g. I do something like this in webpack:
const packageJson = require('./package.json')
const plugins = [
new webpack.DefinePlugin(
{
'__APPVERSION__': JSON.stringify(packageJson.version)
}
)
]
React Component:
<div className='app-version'>{__APPVERSION__}</div>

How to make angularjs typing a global in my project

I'm working on a project that has pulled in Typescript definitions the deprecated typings way and I would like to now move over to using the #types method instead.
Currently we have a typings.json file in the root of the project like so:
{
"globalDependencies": {
"angular": "registry:dt/angular#1.5.0+20161101124950",
"angular-cookies": "registry:dt/angular-cookies#1.4.0+20160317120654",
"angular-material": "registry:dt/angular-material#1.1.0-rc5.0+20161208205836",
"angular-resource": "registry:dt/angular-resource#1.5.0+20160914132003",
"angular-translate": "registry:dt/angular-translate#2.4.0+20160729132354",
"d3": "registry:dt/d3#0.0.0+20160907005744",
"jquery": "registry:dt/jquery#1.10.0+20160929162922",
"lodash": "registry:dt/lodash#4.14.0+20161110215204",
"moment": "registry:dt/moment#2.11.1+20161010105546",
"require": "registry:dt/require#2.1.20+20160919185614"
},
"resolution": "src/client/typings",
"dependencies": {
"angular-local-storage": "registry:dt/angular-local-storage#0.1.5+20160726182927",
"angular-ui-router": "registry:dt/angular-ui-router#1.1.5+20161222093745",
"requirejs": "registry:npm/requirejs#2.2.0+20160319062357"
}
}
As you can clearly see, these are currently installed as globals and are appearing in a src/client/typings folder in our dir structure.
I can already see I have a #types folder under my node_modules which contains some of the typings I have listed in this typings.json file.
In our tsconfig.json file we have an includes config section:
"include": [
"./typings/index.d.ts",
"./app/**/*.module.ts",
"./app/**/*.run.ts",
"./app/**/*.routes.ts",
"./app/**/*.enum.ts",
"./app/**/*.controller.ts",
"./app/**/*.model.ts",
"./app/**/*.directive.ts",
"./app/**/*.filter.ts",
"./app/**/*.service.ts",
"./app/interfaces/**/*.ts"
],
I have since commented out the ./typings/index.d.ts to be sure none of the older typings (not in the #types folders) are being pulled in.
Now, when I look at an .ts file for some angularjs code, I see the angular object is not being resolved anymore:
Having read around, I can just add an import to the file to resolve this (e.g. import * as angular from 'angular'), but it would mean I would need to add to every one of our .ts files that contain any angular code.
Is there an easy\recommended way I can make the angular reference a global in my project, or is best practice to add these fine grained imports across all the files where needed?
Thanks
Create a common .ts file under 'Typings' folder and add all required reference in that file like below.
After that, only add common .ts file reference to all the place where ever all reference required like below.
/// <reference path="../../typings/common.d.ts" />

Resources