Develop a library of components using TypeScript and Less files

I'm currently in the process of creating a React UI library that will consist of various components such as Buttons, Inputs, textareas, etc. This library, which I've temporarily named mylib, will be reused across multiple projects including one called myApp. To ensure type safety, I plan to use TypeScript which requires compilation to ES6. Additionally, I'll be using .less files for styling purposes.

My main concern revolves around handling the .less files. Should I compile them within the myLib itself or delegate this task to the myApp? Is it sufficient to rely solely on the TypeScript compiler, or would it be beneficial to incorporate Webpack for any specific reasons? Despite my efforts, I remain uncertain whether my current approach is the most effective one.

My proposed strategy involves compiling TypeScript code within myLib, while allowing myApp to handle the .less files: Initially, I organize the source code in the src folder and compile it into a destination folder named dist with the TypeScript compiler. Subsequently, by executing a designated script, I copy the relevant .less files from src to dist while preserving their relative paths using the command

cd src && find .  -name '*.less' -exec rsync -R {} ../dist ';'
.

This outlines the directory structure of mylib before compilation:

.
├── README.md
├── dist // destination folder
├── package.json
├── src
│   ├── components
│   │   └── MyComponent
│   │       ├── MyComponent.less
│   │       └── MyComponent.tsx
│   ├── css
│   │   ├── constants.less
│   │   ├── imports.less
│   │   └── reset.less
│   └── index.tsx
└── tsconfig.json

Here's the contents of MyComponent.tsx:

import React from 'react';
import './MyComponent.less';

class MyComponent extends React.Component {
    render() {
        return <div className="MyComponent">My component</div>;
    }
}

export default MyComponent;

This demonstrates the content of MyComponent.less:

@c: .MyComponent;

@{c} {
    font-size: 20px;
    color: tomato;
}

The configuration details specified in tsconfig.json are as follows:

{
  "compilerOptions": {
    "target": "es6",
    "module": "esnext",
    "jsx": "react",
    "esModuleInterop": true,
    "moduleResolution": "node",
    "outDir": "dist"
  }
}

Furthermore, the accompanying package.json contains these specifications:

{
  "name": "@me/mycomponents",
  "version": "0.0.0",
  "description": "Components library",
  "scripts": {
    "build": "tsc -d && cd src && find .  -name '*.less' -exec rsync -R {} ../dist ';' && cd .."
  },
  "devDependencies": {
    "typescript": "^3.6.2",
    "react-dom": "^16.9.0"
  },
  "dependencies": {
    "prop-types": "^15.7.2",
    "react": "^16.9.0",
  }
}

Upon completion of compilation, the structure transforms into:

.
├── README.md
├── dist
│   ├── components
│   │   └── MyComponent
│   │       ├── MyComponent.d.ts
│   │       ├── MyComponent.js
│   │       └── MyComponent.less
│   ├── css
│   │   ├── constants.less
│   │   ├── imports.less
│   │   └── reset.less
│   ├── index.d.ts
│   └── index.js
├── package.json
├── src
│   ├── components
│   │   └── MyComponent
│   │       ├── MyComponent.less
│   │       └── MyComponent.tsx
│   ├── css
│   │   ├── constants.less
│   │   ├── imports.less
│   │   └── reset.less
│   └── index.tsx
└── tsconfig.json

Therefore, once imported into myApp, MyComponent should seamlessly integrate with the ability to compile the associated less files within the same environment.

Does this methodology align with your expectations?

Answer №1

Should I compile the less files in myLib or myApp?

  • Your component library should provide both the .less source code and the .css output.

  • .css is useful for non-less consumers who still want to use your styles.

  • .less is beneficial for less-consumers who may utilize less-specific features like mixins.

Is it sufficient to use only TypeScript compiler, or would it be better to also incorporate Webpack for any reasons?

  • Ideally, your component library should rely solely on the typescript compiler to generate the dist/**/*.js files.

  • Bundling, minification, optimization, polyfilling, and similar concerns should be handled by the consuming applications.

  • Ensure that your tsconfig.json is configured to produce .d.ts declaration files alongside the javascript output to benefit typescript users with typings, code hints, and auto-completion.

    • Add "declaration": true to your `tsconfig.json`.
    • You may also consider enabling source maps for debugging with "sourceMap": true.

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

Encountering a Laravel 9 error: TypeError with webpack-cli - compiler.plugin is not a valid function

I recently downloaded a Laravel 9 template and have been attempting to run and utilize it. However, I keep encountering an issue every time I try running npm run dev. The error message that appears is [webpack-cli] TypeError: compiler.plugin is not a fun ...

Create a complete duplicate of a Django model instance, along with all of its associated

I recently started working on a Django and Python3 project, creating a simple blog to test my skills. Within my project, I have defined two models: class Post(models.Model): post_text = models.TextField() post_likes = models.BigIntegerField() post_ ...

Trigger a drop-down list in React when typing a specific character, like {{ or @, in an input field

Is there a way in React.js to display a list or dropdown when a user types a certain character like '@' or '{{ }}' in the input text area? The user should be able to select an option from this list and have it inserted into the text are ...

Can you explain the distinction between the GenerateSW and InjectManifest choices within the vue ui pwd configuration?

Currently utilizing @vue/cli for building a vue project. I have initiated vue ui to access the vue UI and am in the process of customizing various available options. https://i.sstatic.net/h77AE.png Within Configuration -> PWA, I have come across the a ...

Alert: Prop type validation error: The `component` prop provided to `ForwardRef(Link)` is invalid

We are facing an issue with our NextJS app where it works fine in production, and locally it renders correctly. However, we are encountering some unsightly warnings that we are trying to suppress. client.js:1 Warning: Failed prop type: Invalid prop `compon ...

The Joi validate() function will return a Promise instead of a value when used within an asynchronous function

Trying to understand how async functions and the Joi.validate() function behave. Below is a function used for validating user input. const Joi = require("joi"); const inputJoiSchema= Joi.object().keys({ name: Joi.string(), email: Joi.string().require ...

Error Occurred: ngRepeat directive encountered an invalid expression while attempting to render the

HTML <tr ng-repeat="sale as examples"> <td class="text-right"> @{{sale.sales_person}}</td> <td class="text-right"> @{{sale.sales_total}}</td> <td class="text-right"> @{{sale.sales_target_amount}}</td> ...

"Adding a grid panel to the final node of a tree-grid in extjs: A step-by-step guide

Does anyone have a suggestion on how to add a grid panel to the last node/children of a treepanel dynamically? I would like to append the gridpanel dynamically and for reference, I am providing a link: Jsfiddle I also need to ensure that the gridpanel is ...

When a custom header is added, cookies are not included in cross-origin jQuery AJAX requests

An issue arises when sending an ajax request from our main domain to a subdomain (cross-origin) through jQuery. Despite having CORS implemented and functional, we encounter a problem when attempting to include a custom header in the request. The presence o ...

Tips on personalizing the vue-filemanager interface within Laravel

I'm currently utilizing the Laravel file manager package from here, which provides a pre-compiled JS file or allows for direct use of the vue-component through npm from here. Unfortunately, in both options, the front-end is not customizable. I have i ...

Tips for creating a dynamic system to continuously add more HTML tables in PHP

I am working with an HTML table where the data is retrieved from a database. I need to add new rows to enter additional data, but the numbering does not continue from the last number. My question is how can I increase the numbering in the table. Please ref ...

Exploring Function Overriding in TypeScript

Currently, I'm working on developing a TypeScript method. import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ p ...

The default setting for my bootstrap modal is displayed, not hidden

Is there a way to make my bootstrap model hidden by default and only visible when I click on a link? I'm new to web development and would appreciate any help. tst.html <!DOCTYPE html> <html lang="english"> <head> < ...

The latest version of https-proxy-agent is now 3.0.0, however, the npm audit is still indicating that

After the fix was provided for the NPM package https-proxy-agent on October 18, 2019, upgrading to the latest version still resulted in 6 high vulnerabilities being displayed in the audit warning. Even after running npm audit fix or npm audit fix --force ...

Obtaining static images from the public directory with getStaticProps in Next.js

Next.js provides a thorough method for accessing images from the /public/ folder, where static assets are stored. This involves using Node's fs module and fetching them within the getStaticProps function. Here is an example: export async function get ...

The error in npm run dev is due to outdated versions of Vue, PHP, and other dependencies in the project

Currently, I am working on a project for my company and encountering an issue with running npm run dev. I have already attempted to install npm nuxt and npm node but unfortunately, the problem persists. Any suggestions on how to resolve this would be great ...

The ng-View feature appears to be malfunctioning within AngularJS

I'm extremely new to AngularJS and am having trouble with ng-view. Here is the code from AngularFormsApp.js: var angularFormsApp = angular.module('angularFormsApp', ["ngRoute"]); angularFormsApp.config(function ($routeProvider) { $routeP ...

How can I activate a function or pass a selected value to a different scope variable using AngularUI Bootstrap Datepicker?

Check out this AngularUI Datepicker demo on Plunker: http://plnkr.co/edit/DWqgfTvM5QaO5Hs5dHco?p=preview I'm curious about how to store the selected value in a variable or trigger another function when a date is chosen in the field. I couldn't ...

What is the best way to display values from a Localstorage array in a tabular format using a looping structure

I have set up a local storage key 'fsubs' to store form submissions as an array. Here is how I am doing it: var fsubs = JSON.parse(localStorage.getItem('fsubs') || "[]"); var fcodes = {"barcodeno" : this.form.value.barcode, "reelno" : ...

Encountering issues loading background image with Reactjs and Webpack

I've encountered an issue while trying to load a background image in my React project from a custom CSS file. I am currently using Webpack 4. .bgimage { height: 100vh; background: url('../images/header.jpg'); } Unfortunately, the image ...