Search code examples
typescriptbabeljsrollup

babel 7 not transpiling when used in rollup with typescript plugin


I Cannot seem to get rollup-plugin-babel to work in my typescript project. The .ts code compiles and rollup packages, map files are generated but babel does not transpile it.

Also if I run npx babel lab.js --out-file lab-es5.js babel seem to work just fine.

This my rollup.config.js

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/**',  // Default: undefined
        ignoreGlobal: false,  // Default: 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
        }
    }
];

and this is my .babelrc

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

If you have any clues as to what I am doing wrong I am greatful.


Solution

  • Explanations

    By default, @rollup/plugin-babel have the following extensions enabled:

    .js
    .jsx
    .es6
    .es
    .mjs
    

    And so, there are two things important to set when using @rollup/plugin-babel along with @rollup/plugin-typescript.

    1. You have to tell it to use the TypeScript extension (which is not enabled by default).
    2. You have to tell it which files you want to transpile.

    For some reasons, the documentation says that by default, all files are transpiled. Which is not the case for files having the TypeScript extension. So you have to set the include option manually.

    Fortunately for the second option, you can tell it to use a glob pattern. Setting a folder won't work.

    Example

    Here is an example. In this context, all TypeScript files to transpile are in the src folder.

    "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")
            })
        ];
    };
    

    Links