4

I have a Typescript single-page React app created using create-react-app --typescript. The source code is in .ts and .tsx files in src/.

Now I want to create some utility scripts to use in development. In this case, to download data from our production server and upload it to my local development server, but that's just an example. The scripts have dependencies that the app also has (like an API client library) and I want to import from the App for various constants and helper functions.

Is there a place in create-react-app's structure where I can put such scripts and have them work? I want to be able to call them with npm run scriptname and have them import from the App.

(on our Django backends I would make these into Django management commands, I'm looking for a way to make something similar)

2 Answers 2

5
+25

I create a folder in src called scripts.

It might look like

- scripts
  |- lint.ts
  |- deploy.ts

Then in my package.json

"scripts": {
  // ... add commands:
  "deploy:staging": "ts-node ./src/scripts/deploy.ts --staging",
  "deploy:production": "ts-node ./src/scripts/deploy.ts --production",
  "lint:check": "eslint ./src",
  "lint:format": "eslint ./src --fix"
}

Run like any other script: npm run link:format

Sign up to request clarification or add additional context in comments.

Comments

0

Create-React-App imposes very few restrictions on your project, even if you don't eject. You have the ability to add any custom scripts to package.json's "scripts" section so you can create custom npm/yarn commands for yourself.

I like to put my scripts in a scripts directory next to src as a reminder to myself that this code is not part of my react app (specifically, not part of the bundles that are created when I build for production).

For example, to add a command that populates your dev environment, you can write a nodeJS program that does it, and add the command to your package.json as follows:

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    // ...
    "populatedev": "node scripts/populate-dev-environment"
  },

Or, if you prefer a bash script,

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    // ...
    "populatedev": "./scripts/populateDev.sh"
  },

In either case you would run this command from your CLI as follows:

npm run populatedev

# or if you prefer yarn

yarn populatedev

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.