Access Typescript/JSX code directly from an npm package

I am currently working on creating a simple custom npm package that will be utilized in a Typescript React application built with CRA.

React application BETA:

import {MyText} from 'custom-package';
function App() {
   return (
      <div>
         {MyText()}
      </div>  
  );
}
    

At this point, the directory node_modules/custom-package contains both package.json and index.ts:

index.ts

export const myText = (): string => 'Hello world';

The code above results in the following error:

You may need an additional loader to handle the result...

1. Why is the React app having trouble interpreting the imported Typescript code? Do I really need to transpile it into JavaScript?

My understanding was that Webpack of the BETA app would handle that part. Doesn't Webpack usually take control when it comes to 'export' and 'import' statements? For example, the following scenario works fine:

index.js

export const myText = () => 'Hello world';

2. In this case, Webpack compiles the 'export' statement. Otherwise, the browser wouldn't recognize it without specifying <script type='module'>. Am I correct? If so, why doesn't Webpack also compile index.ts?

I hope my message is clear. Therefore,

3. Is it feasible to directly import Typescript or even JSX code, and if so, how can this be achieved?

Answer №1

Responding to each point in its original form:

1. Why does a React app struggle to interpret imported Typescript code? Why is transpilation to JS necessary?

In Webpack, there is a chain of loaders for files specified in the webpack.config.js, typically based on file extension and project location. The reason why code within node_modules may not be transpiled is likely due to:

  1. Not every application utilizes Typescript extensively.
  2. Many library authors provide a pre-transpiled file referenced in their package.json.
  3. The size of node_modules is significantly larger than project code, making it inefficient for webpack to parse all of it during each build.

2. In the provided example, isn't it Webpack that compiles 'export'? Otherwise, the browser wouldn't recognize it without specifying <script type='module'>. If correct, why doesn't Webpack compile index.ts as well?

Webpack bundles all files together, simplifying the code structure. Despite this bundling process, webpack may avoid parsing typescript directly for efficiency reasons outlined in #1.

3. Can Typescript or JSX code be imported directly and how?

While possible, importing Typescript or JSX directly can slow down build times. This can be achieved by extending the .ts loaders to include node_modules or specific packages within it:

  1. Locate your webpack.config.js file.

  2. Remove any instances of exclude: /node_modules/ from loaders handling ts files.

  3. Add the same loaders to handle tsx files within node_modules:

    module: {
      rules: [
        {
          test: /\.tsx?$/,
          include: /node_modules/,
          loader: 'ts-loader',
        },
      ],
    },
    

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

Can the dimensions of a dialog be customized in Angular Material Design for Angular 5?

I am currently developing a login feature for an Angular 5 application. As part of this, I have implemented an Angular Material Design popup. Within the dialog screen, I have a specific process in place: The system checks the user's email to determi ...

Alert once all observables have finished

I have a collection of observables, each representing a file that needs to be uploaded using an HTTP request. My objectives are: To emit an event for each successfully uploaded file, which will be handled in the parent component. To notify when all file ...

Save and retrieve documents within an electron application

Currently, I am developing an application that will need to download image files (jpg/png) from the web via API during its initial run. These files will then be stored locally so that users can access them without requiring an internet connection in the fu ...

Error message: NextJs throws aReferenceError when trying to access the document object on page refresh

encountered the error ReferenceError: document is not defined when attempting to refresh the page I am working on creating a component using react-quill and then calling that component within a page. This is my component : import React, { useState } from ...

The error "TypeError: Cannot read property 'match' of undefined" occurs when trying to access the match property on an undefined value

Just a few minutes back, I set up a new project in the latest version of Ionic. I included import { HTTP } from '@ionic-native/http' and then proceeded to send a GET request to my backend application. meetingsUrl: 'http://localhost:8080/ ...

I'm unable to address NPM vulnerabilities

My knowledge about npm is limited, and I'm facing an issue that needs resolution: # npm audit report semver <7.5.2 Severity: moderate semver vulnerable to Regular Expression Denial of Service - https://github.com/advisories/GHSA-c2qf-rxjj-qqgw No ...

Choosing between global and local Node packages can be a crucial decision that affects

Recently, I discovered that Angular 2 is installed globally on my system, but I can't remember when I did that or if it's the recommended setup. It seems redundant since Angular can be defined in each project individually. This situation has me ...

Guide on creating a detailed list of categories mapped to specific classes that all adhere to a common generic standard

Most TypeScript factory patterns I've encountered rely on a named mapping between a name and the Class type. A basic implementation example: const myMap = { classOne: ExampleClass, classTwo: AnotherClass } (k: string) => { return new myMap[k] } ...

What data type should I specify for a function that outputs an instance of a class?

When I create a function that returns a class, the structure looks like this: function createClass() { return class implements ISomeInterface {/* ... */} } export { createClass } However, I am now encountering a warning from ESLint: Missing return type ...

Unable to execute functions on observable outcomes

Let's discuss an interface called Vehicle, a class named Car that implements it, and a method within the class titled isColorRed: export interface Vehicle{ color : string; } export class Car implements Vehicle{ color : string; constructo ...

grunt error TS1005: missing semicolon

Currently, I am working with Angular and TypeScript to interact with a REST webservice. Since I am still new to TypeScript, my issue might be basic or my approach could be incorrect. The problem I am facing is receiving an error TS1005: ';' expec ...

Spring Boot fails to recognize path variable data sent from Angular

When working with Angular 7, I encountered a situation where I needed to pass a value from the service class of Angular. Here is how I achieved it: executeHelloWorldBeanServiceWithPathVariable(name){ console.log("name coming from here"+name); retu ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

What are the steps to releasing a React Native component on NPM?

Can you guide me through the process of creating a React Native component and uploading it to NPM? I understand that a GitHub repository is required, but what exact steps are involved? Is there a recommended folder arrangement for this? And how can I ens ...

Error: The Grunt task for Compass has encountered a problem due to difficulty locating the required RubyGem compass version (>= 0

After transferring from an iMac to a new Mac Book Pro with Mavericks, everything seemed fine until I encountered an issue with Grunt crashing when saving files. The auto update was not working as expected. Upon trying to update my system and running grunt ...

Update Observable by assigning it a new value of transformed information using the async pipe and RXJS

My service always returns data in the form of Observable<T>, and unfortunately, I am unable to modify this service. I have a button that triggers a method call to the service whenever it is clicked. This action results in a new Observable being retu ...

Troubleshooting compatibility issues with Node.js modules on Windows: a comprehensive guide

When I use nodejs to write a command line tool, I encounter an error on Windows. However, there seems to be no problem when running it on Linux and Mac OSX systems. You can find the package at https://www.npmjs.com/package/idoc To globally install, use t ...

Sort through an array of objects by a specific field in each object

Imagine having an array containing different objects: [ { "category": 121, "item": "item1" }, { "category": 128, "item": "item2" }, { "category": 130, "item": "item2" }, { "category": 130, "item": "item2" } ] Your goal is to filter this array and ...

Navigating through tslint: adhere to the one-variable-per-declaration rule

What is the best way to write code following this rule? let exampleArray = [...]; for (let j = 0, k = exampleArray.length; j < k; j++) { ... } ...

Unable to run 'ng serve -o', however 'ng serve' functions correctly

Encountering an issue with Angular when attempting to configure the Micro frontend Framework (module federation) for both the remote and host applications. They are not located in the same workspace. When running the remote app with "ng serve -o", an error ...