What are the steps for importing a file into a React app that is built using Create React App as plain text?

Objectives

  1. I aim to showcase code snippets from the project itself for reference.
  2. I intend to keep the displayed code up-to-date with its implementation.
  3. I prefer not to remove myself from create-react-app

This React project, built using create-react-app and typescript, is designed to exhibit custom components that can be reused in other projects. My objective is to seamlessly integrate these components next to their corresponding code snippets.

Is there a way to load files without needing access to the webpack configuration or utilizing fs.readFile?

Answer №1

After some searching, I finally managed to get everything working. There were two key components that needed to be in place for it to function properly.

Using the correct loader

In this particular situation, I needed to utilize the raw-loader. So, I added it as a dev dependency using the command yarn add -D raw-loader.

To import the file successfully, I had to modify the webpack configuration like so:

// eslint-disable-next-line import/no-webpack-loader-syntax
import toolbarItems from '!!raw-loader!../ToolbarItems';

This code snippet loads the entire file into the variable toolbarItems. The use of !! before the loader ensures that no other webpack loaders process it in this specific scenario. While this approach may work in a regular JavaScript project, it proved to be slightly different when dealing with TypeScript...

Providing a module for TypeScript

I encountered a TypeScript error during the process:

Failed to compile.

/Users/cory/Code/something/custom-theme/src/pages/NavigationDemo.tsx
TypeScript error in /Users/cory/Code/something/custom-theme/src/pages/NavigationDemo.tsx(9,26):
Cannot find module '!!raw-loader!../ToolbarItems'.  TS2307

     7 |
     8 | // eslint-disable-next-line import/no-webpack-loader-syntax
  >  9 | import toolbarItems from '!!raw-loader!../ToolbarItems';
       |                          ^
    10 |
    11 | const useStyles = makeStyles({
    12 |   root: {

To resolve this issue, simply creating a module for the loader in a file named ToolbarItems.ts.d.ts did the trick:

declare module '!!raw-loader!*' {
  const content: string;
  export default content;
}

source

Answer №2

If you're utilizing create-react-app in your project, consider incorporating the babel plugin Raw.Macro for an effective solution.

With Raw.Macro, you can effortlessly access file content without the need to eject from create-react-app, eliminating unnecessary boilerplate code and declaration of "d.ts" files as seen in alternative methods.

Keep in mind that a minor inconvenience exists where you'll have to restart your webpack dev server upon file changes, as the file's content gets embedded during the build process.

import raw from 'raw.macro';

function bar(){
    const jsonContent = raw('../utils/data.json');
    console.log(jsonContent);
}

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

Guide: Writing code that caters to different types of media in React using Material-UI

After reviewing the documentation, I believed that the optimal solution in later versions of material-ui was to use useMediaQuery, but unfortunately, I am unable to implement it correctly. My objective is to hide a menu when the page is being printed, so I ...

Cannot get Firebase's set() method to work when called within onAuthStateChanged() function

As I embark on developing my first significant web application using ReactJS with Firebase as the backend database, everything was progressing smoothly until a troublesome issue surfaced. The hurdle I encountered involves saving user information upon thei ...

Utilize Shopify's API to seamlessly collect email inquiries directly through a custom contact page

Currently, I am facing a challenge in making my contact us page functional within my Shopify app. The link provides guidance on creating a contact page in Shopify, but as I am developing a Shopify app using nextjs, I am struggling to integrate my own co ...

Why is it not possible to convert from any[] to MyType[] in TypeScript?

Within TypeScript, the any type allows for casting to and from any arbitrary type. For example, you can cast from a variable of type any to a variable of type MyArbitraryType like so: var myThing: MyArbitraryType; var anyThing: any; myThing = anyThing; / ...

Having trouble setting the default value of a select element with 'selected' in Angular's bootstrap?

Click here I've been facing some difficulties in making the 'selected' tag work to pre-select my default select value. It seems like it might be related to the unique pipe I'm using and how Angular handles it. I have experimented with ...

Converting a CodePen JavaScript file into a React application involves adapting the code structure to fit the React framework and incorporating necessary dependencies

Exploring the functionality of the FilePond module within a React application by uploading a basic file is something I am eager to showcase. To see an example, I have prepared a CodePen demonstration: https://codepen.io/rikschennink/pen/WXavEx If you nav ...

I find the JSX syntax to be quite perplexing

While examining some code, I came across the following: const cardSource = { beginDrag(props) { return { text: props.text }; } }; When working with JSX block code or building objects, I usually use {}. The cardSource variable in this co ...

React Drawer triggering excessive re-renders

I am trying to implement a button that, when clicked, will display a Drawer from the bottom. Here is the code snippet I have written: import * as React from "react"; import Box from "@mui/material/Box"; import Drawer from "@mui/mat ...

What is the most effective approach to building this function in React JS rather than the existing .map method?

Hello, I'm fairly new to all of this so please bear with me. I've been working on developing a search function for my app, but I've encountered a problem. The search function in my header component is being rendered like this in my index: &l ...

"Encountering issues with getStaticPaths not generating any paths

I have a folder named data which contains a file called events.ts: export const EventsData: Event[] = [ { name: 'School-Uniform-Distribution', images: ['/community/conferences/react-foo.png', "/community/conferences/react ...

What is the process for setting up nested routes using React router?

I have multiple layouts that need to display different screens. Each layout has its own header, footer, and other shared elements similar pages should have. Below is the code I have created: <BrowserRouter> <Route path={['/index', &ap ...

Unable to input any text in the field when utilizing the value={} attribute

In my NextJS project, I am working on creating a form to update supplier information. Here is the input field in question: <input type="text" ref={nameDisplayedRef} className='p-2 rounded' name='nameDisplay ...

Creating custom disabled button styles using TailwindUI in a NextJS application

I had a NextJS application that utilized Atomic CSS and featured a button which becomes disabled if a form is left unfilled: <Button className="primary" onClick={handleCreateCommunity} disabled={!phone || !communi ...

Incorporating TypeScript into a project that already contains .js files

I currently have a NodeJS project with .js files written in ES6. I am interested in integrating typescript into this existing project. What steps should I follow? Can I simply introduce .ts files within the same directory structure? One issue I have encou ...

Issues with applying different styles in a React Component based on prop values are hindering the desired outcome

I am currently working on a Display component that is supposed to show an item. The item should be styled with the css property text-decoration-line, applying line-through when the Available prop is set to false, and no decoration when set to true. Howev ...

Customizing the scrollbar within a modal using reactjs-popup

I am currently working on a CustomPopup functional component that includes a reactjs-popup: function CustomPopup({setFalse, item}){return(<Popup open={true} onClose={() => {setFalse(false)}} modal closeOnDocumentClick nested> {item === "howto ...

Troubleshooting issues with resolving relative paths in React using Webpack

In my current React project utilizing Webpack, I am facing an issue with referencing a component located in frontend/app/components/editor/index.js from another component. The only way I have been able to reference this component is by using a cumbersome r ...

Modifying an Object Property from a Child Component in React using useState

Hey everyone, I'm struggling with changing a single object property from another on the child side. import ComboData from './ComboData.js' export default function BasicTabs() { const [country, setCountry] = useState({ selectedID: 0, data: ...

What is the best way to update an array within an object using Redux?

I am currently working on a code for redux that involves an array. const initialState = [{ id: '1', title: '', description: '' }]; My goal is to update the array to contain two objects like this: [{ id: '1', title: ...

Refresh AdSense Ads when navigating in Next JS

We have successfully integrated Google AdSense into our Next.JS website, but we are looking to automatically reload ads whenever a new route is accessed. Here is the approach I took: const Advertisement = props => { const { userLoaded, currentUserIsS ...