Utilize a module within a script in the continuous integration setup of a React application

I've created a module to verify if all the necessary environment variables are properly set in a React application. Here's a simple example of how it works:

const getEnvironmentVariable = (key: string): string => {
  if (process.env[key]) {
    return process.env[key] as string;
  }
  throw new Error(`Missing mandatory environment variable ${key}`);
}

type Config = {
  foo: string
}

const config: Config = {
  foo: getEnvironmentVariable('REACT_APP_FOO')
}

export default config;

This code is effective during app execution, but it would be beneficial to also run it in CI to identify missing variables before deployment :)

However, when attempting to run it using ts-node, an error occurs:

ts-node src/config/environmentVariables.ts
(node:30355) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
(...)/src/config/environmentVariables.ts:38
export default config;
^^^^^^

SyntaxError: Unexpected token 'export'

Does anyone have suggestions on how to address this without resorting to tactics like temporary files?

Best regards, Julien

Answer №1

At long last, I implemented a solution that looked something like this:

// tsconfig.scripts.json
{
  "compilerOptions": {
    "module": "commonjs",
    "baseUrl": ".",
    "rootDir": "./",
    "outDir": "build-script",
    "target": "es6",
    "sourceMap": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true,
    "resolveJsonModule": true
  },
  "include": ["./scripts/validateEnvVars.ts"]
}

Furthermore, within the CI environment (specifically github actions):

      - name: Validate Env Vars
        run: |
          set -o allexport; source .env; set +o allexport
          tsc --project ./tsconfig.scripts.json
          node build-script/scripts/validateEnvVars.js

Cheers!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for sending props, state, or arguments to a TypeScript React component

Hey there, total newbie here... I'm currently working on a school project and I've hit a bit of a roadblock... I'm attempting to pass some props from one component to another, but for some reason, it's not working properly. The goal ...

Troubleshooting error in Next.js when adding "sizes" attribute to Image component with layout set to "responsive"

When you use the following code: <Image src="/images/lorem.jpg" height={150} width={850} layout="responsive" sizes="50vw" // <== ...

Implementing TypeScript/Angular client generation using Swagger/OpenAPI in the build pipeline

Generating Java/Spring Server-Stubs with swagger-codegen-maven-plugin In my Spring Boot Java project, I utilize the swagger-codegen-maven-plugin to automatically generate the server stubs for Spring MVC controller interfaces from my Swagger 2.0 api.yml fi ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

How come my Next.js route handler is not able to access the request body from my button component?

I'm having difficulty extracting the request body from a route handler in Next.js 13. Below is my button component: 'use client' export default function Button() { const handleClick = () => { const requestOptions = { ...

Is there a way to adjust user privileges within a MenuItem?

One of my tasks is to set a default value based on the previous selection in the Userlevel dropdown. The value will be determined by the Username selected, and I need to dynamically update the default value label accordingly. For example, if "dev_sams" is ...

Cannot render <Image> inside <Section> component

As a beginner in React, I am attempting to create an app following a tutorial. In my component, I utilized the figure tag but it's not showing up when inspecting element in Chrome. Here are the code snippets: The tutorial includes a div tag as a chil ...

Encountering an Invalid hook call error - Ensure that you are only utilizing hooks within the body of a functional component specifically designed for use with

Understanding the Error sp-webpart-workbench-assembly_default.js:26401 [1599066762186][OtherGlobalError.window.onerro] Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of ...

Has the web application continued to run in the background even after toggling between tabs on the browser?

Does the app continue running in the background even when I'm not on that specific tab? Or does it pause when I switch between tabs, requiring a new request to the server for any updated data from the database upon returning to that tab? Edit: Curren ...

Continuously calling setState within the useEffect hooks causes an infinite loop

After extensive research and reading various articles on the topic, I am still facing the issue of infinite loops with useEffect and useState. One article that caught my attention was this one. Prior to reading the article, my useState function inside use ...

Transferring cookies and sessions across different subdomains

Looking to enable cookies/sessions in the browser is my current objective. Preface: The Frontend: https://www.example.com The Backend: https://api.example.com Upon a request from the frontend to the backend, a session is initiated and a cookie is suppo ...

Error: Unable to access 'length' property of null in Next.js issue

I am encountering an error in my Next.js files: 117 | }; 118 | > 119 | if (data.length <= 0) { | ^ 120 | return null; 121 | } 122 | If I want to display it with an image, the error looks like this:https://i.stack ...

Any advice on resolving the issue of "Failed to parse source map from..." errors in my ReactJS/TS project?

I am working on a ReactJS project and encountered an issue while trying to implement a Barcode-Scanner npm module called html5-qrcode. The error message I keep receiving is: Failed to parse source map from 'C:\...\node_modules\html5-qr ...

Facing an issue with the TypeScript error in the Tailwind-Styled-Component Npm package. Any suggestions on how to troub

module.styles.ts File import tw from "tailwind-styled-components"; export const Wrapper = tw.div` bg-green-500 `; export const Link = tw.a` text-blue-500 `; home.jsx File import React from "react"; import { Wrapper, Link } from &qu ...

Can an interface be designed to have the option of containing either one property or another?

I am in need of an interface that resembles the following structure: interface EitherOr { first: string; second: number; } However, I want to make sure that this interface can only have either the property first or second. Do you think achieving this ...

Is it possible to utilize an @Input() in Angular with multiple types?

Is it possible for a parent component to pass an object in @Input to the child component that may not always be the same? For instance, can I use: @Input() obj: string | number; In my scenario, I have two different objects as potential inputs: @Input() ob ...

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...

When utilizing a 'Token' in the provider() aliasing within Angular 2, the Typescript compiler may display an error message stating 'Unresolved variable or type'. This issue can arise when defining

When working with Typscript, I've encountered an issue where it can't handle a 'Token' in the context of an Angular2 provide() aliasing function. I'm unsure if there's a specific setting in the typescript compiler to address t ...

Having trouble with firebase admin code completions not functioning properly in vscode?

I've attempted to install the Typescript integration for Firebase using: npm install --save-dev @types/firebase Unfortunately, I have not had any success. The "firebase-admin" and "firebase-functions" packages do not provide code completion or intel ...