Rollup plugin for TypeScript fails to transpile Babel 7 code

I've been encountering issues trying to use rollup-plugin-babel in my typescript project. Despite the .ts code compiling and rollup generating map files, babel does not seem to transpile it.

Interestingly, when I execute

npx babel lab.js --out-file lab-es5.js
, babel works perfectly fine.

This is the content of my rollup.config.js file:

import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript2'
import sourcemaps from 'rollup-plugin-sourcemaps';
import babel from 'rollup-plugin-babel';

var plugins = [
    nodeResolve({
        module: true,
        jsnext: true,
        main: true,
        preferBuiltins: false
    }),
    commonjs({
        include: 'node_modules/**',
        ignoreGlobal: false,
    }),
    typescript(/*{ plugin options }*/),
    babel({
        exclude: 'node_modules/**',
        runtimeHelpers: true
    }),
    sourcemaps()
];

export default [
    {
        input: 'src/lab.ts',
        plugins,
        output: {
            name: "TablePager",
            file: 'lab.js',
            format: 'iife',
            sourcemap: true
        }
    }
];

Here is the content of my .babelrc file:

{
    "presets": ["@babel/preset-env"]
}

If you have any insights on what might be causing this issue, I would greatly appreciate your help.

Answer №1

Insights

The default settings for @rollup/plugin-babel include the following file extensions:

.js
.jsx
.es6
.es
.mjs

When using @rollup/plugin-babel in conjunction with @rollup/plugin-typescript, there are two key aspects to consider.

  1. You must specify to use the TypeScript extension as it is not enabled by default.
  2. You need to indicate which files should be transpiled.

Contrary to what the documentation implies, not all files are automatically transpiled, especially those with the TypeScript extension. Therefore, you must manually set the include option.

Thankfully, for the second aspect, you can utilize a glob pattern instead of specifying a folder directly.

Illustration

Here's an example scenario where all TypeScript files meant for transpilation reside in the src directory.

"use strict";

import babel from "@rollup/plugin-babel";
import typescript from "@rollup/plugin-typescript";

import { resolve } from "path";

export default {
    plugins: [
        typescript(),
        babel({
            extensions: [".ts"],
            include: resolve("src", "**", "*.ts")
        })
    ];
};

References

Answer №2

Take a look at the TypeScript-Babel-Starter by Microsoft on GitHub, specifically the rollup section.

import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import pkg from './package.json';

const extensions = [
  '.js', '.jsx', '.ts', '.tsx',
];

const name = 'RollupTypeScriptBabel';

export default {
  input: './src/index.ts',

  // Specify here external modules which you don't want to include in your bundle (for instance: 'lodash', 'moment' etc.)
  // https://rollupjs.org/guide/en#external-e-external
  external: [],

  plugins: [
    // Allows node_modules resolution
    resolve({ extensions }),

    // Allow bundling cjs modules. Rollup doesn't understand cjs
    commonjs(),

    // Compile TypeScript/JavaScript files
    babel({ extensions, include: ['src/**/*'] }),
  ],

  output: [{
    file: pkg.main,
    format: 'cjs',
  }, {
    file: pkg.module,
    format: 'es',
  }, {
    file: pkg.browser,
    format: 'iife',
    name,

    // https://rollupjs.org/guide/en#output-globals-g-globals
    globals: {},
  }],
};

.babelrc

{
  "presets": [
    "@babel/env",
    "@babel/typescript"
  ],
  "plugins": [
    "@babel/proposal-class-properties",
    "@babel/proposal-object-rest-spread"
  ]
}

Answer №3

Make sure to include @babel/preset-typescript in your .babelrc file. Simply install the package and update your configuration as follows:

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-typescript"
    ]
}

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 on positioning a span element to the left using the margin auto property in CSS for Angular 4

Having trouble with moving numbers highlighted to the left with names in CSS. I've tried using flex direction and margin auto but can't achieve the desired result. https://i.sstatic.net/kRJOb.png Here is my HTML code: <section class="favorit ...

Using the parameter of type 'never' is necessary as per the TypeScript error message, which states that the argument of type 'string' cannot be assigned to it. This error persists even when

https://i.sstatic.net/tkX07.png const index = selectedActivities.value.indexOf(activity_id); I encountered a TypeScript error saying 'Argument of type 'string' is not assignable to parameter of type 'never'. How can I fix this iss ...

What causes tsc to generate different json files based on its execution location?

Scenario: You have a typescript project set up to generate JSON files. The tsconfig.json is properly configured and all dependencies are in place. You've even referred to this related Q&A and ensured that your typescript files are importing the json f ...

What is the advantage of utilizing the "extends" keyword over directly stating the type?

Recently, I came across this interesting article at https://www.typescriptlang.org/docs/handbook/generics.html#generic-constraints I can't help but wonder why the extends keyword is necessary in this context. interface Lengthwise { length: number; ...

Is it feasible to alter the file name while utilizing express-fileUpload library?

Is there a way to modify the file name of an uploaded file on the server side? app.post(URL, (req, res) => { let fileName = req.files.file.name; req.fileUpload; res.statusCode = HTTP_OK; res.send("Good Job") }) The settings I have in uploadF ...

Oops! Unable to locate the module specifier "highlight.js" in the ES6 module compiled from TypeScript

I'm currently experimenting with the highlight.js library for code highlighting, and while it does support ES modules, I encountered an issue when trying to use it in an ES6 module compiled from TypeScript. The error message that pops up is: Uncaught ...

Embedding Interfaces within Interfaces

I am faced with a TypeScript interface challenge: interface SupplierSettings { id_supplier_settings?: number; is_auto_order: boolean; order_cron: string; email: string; get_next_run_date?: string; dont_wait_for_mail_response: boolea ...

Changing the selection on multiple input fields in Angular

I am working with two select elements in my form. Based on the selected value from the first select, I am filtering data for the second select. Additionally, I have an option to add the same row of form if desired. My issue is that when I select a value fr ...

What is the timing for the execution of top-level non-export code in TypeScript?

I am currently puzzled about the execution of code in files. Let's say we have a file1.ts with the following content: export interface myInterface {} export function myFunction() {} export const myConst: {} // ... and more exports // top-level non- ...

Creating a one-of-a-kind entry by adding a number in JavaScript

I am looking for a way to automatically add an incrementing number to filenames in my database if the filename already exists. For example, if I try to add a file with the name DOC and it is already present as DOC-1, then the new filename should be DOC-2. ...

What is preventing MenuItemLink from being displayed in the menu?

I have created a unique page for users to purchase subscriptions, but I am having trouble accessing that page because the button is not appearing in the menu. I followed the steps outlined in the official guide, but only the dashboard and resources buttons ...

Unable to utilize AgmMarkerSpiderModule

I followed the instructions to add the AgmMarkerSpiderModule from the official package documentation. However, when I compile, I encountered the following error message: /directives/marker-spider.ts:14:24 - error TS2307: Cannot find module '@agm/core/ ...

Guide on how to address the problem of the @tawk.to/tawk-messenger-react module's absence of TypeScript definitions

Is there a way to fix the issue of missing TypeScript definitions for the @tawk.to/tawk-messenger-react module? The module '@tawk.to/tawk-messenger-react' does not have a declaration file. 'c:/develop/eachblock/aquatrack/management-tool-app ...

Signal a return type error when the provided element label does not correspond with an existing entity

I am working on a component that accepts three props: children (React elements), index, and label. The goal is for the component to return the child element at a specific index when index is passed, and to return the element with a specific label when la ...

Fetching all data from a SQLite database in a Listview using React Native

I have been utilizing the library found at https://github.com/andpor/react-native-sqlite-storage in my react native project. To retrieve a single row from the database, I use the following code: db.transaction((tx) => { tx.executeSql('SEL ...

Utilize the ref attribute when working with Material UI InputLabel components

Is there a way to access the ref parameter of an InputLabel from the @material-ui/core library using TypeScript? When I attempt to do so, the following code produces an error related to ref: TS2769: No overload matches this call. export class ComboBo ...

The property y is not found on type x during property deconstruction

After creating a straightforward projectname.tsx file to contain my interfaces/types, I encountered an issue: export interface Movie { id: number; title: string; posterPath: string; } In another component, I aimed to utilize the Movie interface to s ...

How can Angular2 detect when an entity is clicked within a window?

There are multiple items generated using *ngFor: <my-item *ngFor="let item of myArray" [p]="item"></my-item> I am able to handle a click event like this: <my-item ... (click)="doWork(item)"></my-item> However, I want to avoid a ...

Retrieving class properties in typescript

I am working with a class that has numerous methods, which I refer to as myClass. When calling it, the syntax is as follows: myClass[key]() Is there a way to retrieve the valid values for key? I tried using keyof myClass, but received an error message st ...

How can we efficiently load paginated data from a database while still implementing pagination using Angular Material?

I have a large table with more than 1000 entries that I want to display using a <mat-table></mat-table>. Since loading all the entries at once would be too much, I am looking to implement pagination and load only 20 entries per page. The chal ...