What is the process for integrating custom TypeScript declaration files into the final build with rollup.js?

I am working on a project in Typescript where the files are built using rollup.js. Within my project, I have certain declaration files set up and I am curious if it is feasible to include these declaration files in the final built declaration file.

Declaration file:

// src/styled-components.d.ts

import 'styled-components';

declare module 'styled-components' {
    export interface DefaultTheme {
        colors: {
            gray: string;
            primary: string;
        };
    }
}

Current final built declaration file:

// dist/index.d.ts

export { default as DesignSystemProvider, } from './providers/DesignSystemProvider';
export { default as Button } from './components/Button';
export { default as Checkbox } from './components/Checkbox';

Expected final built declaration file:

// dist/index.d.ts

import 'styled-components';

declare module 'styled-components' {
    export interface DefaultTheme {
        colors: {
            gray: string;
            primary: string;
        };
    }
}

export { default as DesignSystemProvider, } from './providers/DesignSystemProvider';
export { default as Button } from './components/Button';
export { default as Checkbox } from './components/Checkbox';

Reason

By incorporating this library into another, I aim to access the typings of styled-components props.

Configuration Files

// rollup.config.js

import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import postcss from 'rollup-plugin-postcss';
import typescript from 'rollup-plugin-typescript2';
import url from 'rollup-plugin-url';
import { sizeSnapshot } from 'rollup-plugin-size-snapshot';

import pkg from './package.json';

export default {
    input: 'src/index.ts',
    output: [
        {
            file: pkg.module,
            format: 'es',
            exports: 'named',
        },
    ],
    plugins: [
        peerDepsExternal({
            includeDependencies: true,
        }),
        url(),
        nodeResolve({
            // browser: true solves
            // indexof (imported by ../../../node_modules/component-classes/index.js, indexof?commonjs-external)
            browser: true,
            extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
        }),
        typescript({
            exclude: ['**/*.stories.tsx', '**/*.spec.tsx'],
            rollupCommonJSResolveHack: true,
            clean: true,
        }),
        commonjs({
            include: /\**node_modules\**/,
        }),
        postcss(),
        sizeSnapshot(),
    ],
};
// tsconfig.json

{
    "compilerOptions": {
        "outDir": "build",
        "module": "esnext",
        "target": "es5",
        "lib": ["es6", "dom", "es2016", "es2017"],
        "sourceMap": true,
        "allowJs": false,
        "jsx": "react",
        "declaration": true,
        "moduleResolution": "node",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "noImplicitAny": true,
        "strictNullChecks": true,
        "suppressImplicitAnyIndexErrors": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true
    },
    "include": ["src"],
    "exclude": ["node_modules", "build", "dist", "example", "rollup.config.js"]
}

Answer №1

I managed to get it to work by following these steps

  1. Change the name of the file src/styled-components.d.ts to styled-components.ts
  2. Include export {}; at the end of the styled-components.ts file
  3. Insert import './styled-components;` at the beginning of the main file.

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

Utilizing Angular Pipes for Utilizing Location

The Location service in Angular is described as "A service that applications can use to interact with a browser's URL." One of its methods, getState(), provides "the current state of the location history," while another method, subscribe(), allows us ...

Error: In Typescript, it is not possible to assign the type 'false' to type 'true'

Currently, I am exploring Angular 2 and encountered a situation where I set the variable isLoading to true initially, and then switch it to false after fetching required data. However, upon executing this process, I encountered the following error message: ...

Using JavaScript to round up the number

I need help rounding numbers in a specific way: Value Expected 0,523% 1% 2,235% 2,5% -0,081% -0,5% -1,081% -1,5% How can I achieve this using JavaScript? Possible Solution: static round (num) { const abs = Math.abs(num); const sign = num ...

Versatile functions and unique index classifications

I need help creating a versatile function that takes a type argument "T" representing an object. It should use keyof T to determine the first argument named "property". However, I am struggling with defining the type of the second argument, called "value", ...

A step-by-step guide on effectively adopting the strategy design pattern

Seeking guidance on the implementation of the strategy design pattern to ensure correctness. Consider a scenario where the class FormBuilder employs strategies from the following list in order to construct the form: SimpleFormStrategy ExtendedFormStrate ...

Getting node siblings within an Angular Material nested tree: A comprehensive guide

Struggling to retrieve the list of sibling nodes for a specific Angular Material tree node within a nested tree structure. After exploring the Angular Material official documentation, particularly experimenting with the "Tree with nested nodes," I found t ...

What is the process of changing a number to the double data type in JavaScript or TypeScript?

Within a single input field, users can enter various numbers such as 12, 12.1, 12.30, and 12.34. The challenge is to pass this value in a service call where only the value can be sent as a number but with two decimal points. let a = input //a will be a ty ...

Exploring the world of interfaces in nested mapping functions

Currently, I'm faced with the challenge of mapping an array inside another map with an array. These are the specific interfaces that I am working with: interface Props { columns: Array<{field: string, headerName: string, width: number}>; row ...

Angular 7 is throwing an error message stating that it is unable to locate the module named './auth.service'

Currently, I am facing a challenge while using Angular Guards to secure my pages from unauthorized access. import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot , Router } from '@angular/router'; import { Observable } from 'rxjs& ...

Leveraging AWS CDK to seamlessly integrate an established data pipeline into your infrastructure

I currently have a data pipeline set up manually, but now I want to transition to using CDK code for management. How can I achieve this using the AWS CDK TypeScript library to locate and manage this data pipeline? For example, with AWS SNS, we can utilize ...

Guidelines for securing login access where the "IsApproved" field must be true before authorization

During the account registration process, I initially set the default value to false for the field IsApproved. I need to create security rules that allow login only for users with IsApproved:true, and redirect those with IsApproved:false to the accessdenied ...

Is it possible that using the component getter to display a router link may not be effective?

My email application is being developed using angular 6, featuring a list of mailboxes for users to access by clicking on the provided link. Interestingly, when utilizing component version A to display the mailbox list, clicking on the router link does no ...

Linking together observables to handle the response received from the PrimeNG confirmation service

Currently, I am utilizing the confirm.service from PrimeNG in my application. My goal is to display an array of messages to the user with only one message shown at a time along with an Accept button. However, my current code is only displaying the last me ...

Is there a way to enable Tail Recursion Optimization in TypeScript?

const isPositive = (n: number) => n > 0; function fitsIn(dividend: number, divisor: number, count: number, accum: number): number { if (accum + divisor > dividend) { return count; } return ...

Encountered an error in React where the declaration file for a module could not be located

New to Typescript and trying to incorporate a splitter into my project. I'm utilizing SplitPane from "react-split-pane/lib/SplitPane" and Pane from "react-split-pane/lib/Pane" in my Typescript project, but encountering an error: Could not find a de ...

Components in Angular do not refresh after using router.navigate

I currently have two main components in my Angular project: users.components.ts and register.components.ts. The users.components.ts displays a table of users, while the register.components.ts is where users can be added or edited. After making changes to ...

Rule in Eslint for Typescript that enforces explicit typing and prohibits the use of implicit "any

Starting a fresh typescript project with eslint, I'm facing an issue in setting up eslint rules for the tsc command to run smoothly without errors. Specifically, I'm encountering difficulty with the "noImplicitAny" rule defined in tsconfig.json, ...

Will the component re-render before executing the next lines when using setState or dispatch with the useReducer hook?

Upon using the useState and useReducer hooks, I encountered an issue where any code lines following the state update function (setState, dispatch) would be executed in the subsequent re-rendering, with the previous state intact before the update. Essential ...

What causes the website to malfunction when I refresh the page?

I utilized a Fuse template to construct my angular project. However, upon reloading the page, I encountered broken website elements. The error message displayed is as follows: Server Error 404 - File or directory not found. The resource you are looking fo ...

Display customizable template according to variable

The answer provided for the issue regarding dynamic template generation based on value instead of variable in this thread was really helpful. However, I'm facing challenges in getting it to work. Here's a simplified example: export class A { } ...