Setting up TypeScript along with Babel and Webpack: A step-by-step guide

Here are the dependencies listed in my project:

"devDependencies": {
  "@types/node": "^4.0.27-alpha",
  "babel-core": "^6.10.4",
  "babel-loader": "^6.2.4",
  "babel-polyfill": "^6.9.1",
  "babel-preset-es2015": "^6.9.0",
  "babel-preset-stage-0": "^6.5.0",
  "ts-loader": "^0.8.2",
  "typescript": "^2.0.0",
  "webpack": "^1.13.1"
}

.babelrc file content:

{
  "presets": [
    "es2015",
    "stage-0"
  ]
}

tsconfig.json configuration:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noImplicitAny": false,
        "sourceMap": false,
        "outDir": "built"
    },
    "exclude": [
        "node_modules"
    ]
}

Contents of webpack.config.js file:

module.exports = {
  entry: ['babel-polyfill', './src/'],
  output: {
    path: __dirname,
    filename: './built/bundle.js',
  },
  resolve: {
    modulesDirectories: ['node_modules'],
    extensions: ['', '.js', '.ts'],
  },
  module: {
    loaders: [{
      test: /\.tsx?$/, loaders: ['ts-loader', 'babel-loader'], exclude: /node_modules/
    }],
  }
};

/src/index.ts implementation:

async function foo() {
  const value = await bar();
  console.log(value);
}

function bar() {
  return new Promise((resolve, reject) => {
    return resolve(4);
  });
}

(async function run() {
  await foo();
}());

Despite a successful build and run (logging 4 correctly), there are some errors encountered with Webpack:

ERROR in ./src/index.ts
(4,32): error TS2304: Cannot find name 'regeneratorRuntime'.

ERROR in ./src/index.ts
(6,12): error TS2304: Cannot find name 'regeneratorRuntime'.

ERROR in ./src/index.ts
(31,451): error TS2346: Supplied parameters do not match any signature of call target.

ERROR in ./src/index.ts
(40,33): error TS2304: Cannot find name 'regeneratorRuntime'.

ERROR in ./src/index.ts
(41,12): error TS2304: Cannot find name 'regeneratorRuntime'.

The issue seems to be related to the usage of babel-polyfill. What could be missing here?

Answer №1

Babel 7 no longer requires ts-loader.

With the release of Babel 7, utilizing ts-loader is now redundant as Babel 7 has native TypeScript support. For a comprehensive guide on setting up TypeScript with Babel 7 and Webpack, refer to this resource.

A walkthrough of the setup process without using ts-loader.

To get started, install Babel's TypeScript support. While only @babel/preset-typescript is mandatory, the other three provide additional functionality that complements TypeScript.

npm install --save-dev @babel/preset-typescript 
npm install --save-dev @babel/preset-env 
npm install --save-dev @babel/plugin-proposal-class-properties 
npm install --save-dev @babel/plugin-proposal-object-rest-spread

Next, configure the necessary plugins and presets in your .babelrc file.

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

Finally, update your webpack.config.js accordingly (other code sections are omitted for clarity).

module: {
  rules: [
  {
     test: /\.(js|jsx|tsx|ts)$/,
     exclude: /node_modules/,
     loader: 'babel-loader'
    }
  ]
},
resolve: {
  extensions: ['*', '.js', '.jsx', '.tsx', '.ts'],
},

Answer №2

When configuring loaders in webpack, it's important to consider the order of execution. Loaders always run from right to left, so make sure to place them in the correct sequence.

test: /\.tsx?$/, loaders: ['babel-loader', 'ts-loader'], exclude: /node_modules/

This adjustment resolved the issue by ensuring that ts-loader is executed first.

Below is the updated webpack.config.js file:

module.exports = {
  entry: ['babel-polyfill', './src/'],
  output: {
    path: __dirname,
    filename: './dist/index.js',
  },
  resolve: {
    extensions: ['', '.js', '.ts'],
  },
  module: {
    loaders: [{
      test: /\.ts$/, loaders: ['babel-loader', 'ts-loader'], exclude: /node_modules/
    }],
  }
};

For a sample project using this configuration, visit brunolm/typescript-babel-webpack.

Answer №3

(4,32): error TS2304: Issue locating 'regeneratorRuntime'.

This indicates that the result of babel is being passed to ts. The sequence here is incorrect

Solution

Your compilation setup should direct TS output to Babel.

Alternatively, you could compile TypeScript using just Babel with @babel/preset-typescript.

Learn More

Further information on compiling TypeScript with Babel : https://babeljs.io/docs/en/babel-preset-typescript

Answer №4

This post may be a bit outdated...
For those looking to integrate babel with ts-loader in the year 2023:

Installation Steps

npm install -D babel-loader @babel/core @babel/preset-env

Setting up Webpack Loaders

{
  entry: './src/index.tsx',
  // ... your other webpack configs
  module: {
    // ... your other module configs
    rules: [
      // ... your other roles configs
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [
                ['@babel/preset-env', { targets: 'defaults' }],
              ],
            },
          },
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true,
            },
          },
        ],
      },
    ],
  },
}

Successfully tested using electron-forge.
(Environment includes NodeJS 19.0.0, TypeScript 5.0.2, @babel/core 7.21.3, babel-loader 9.1.2, and ts-loader 9.2.2)

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

Navigating an HTML table with the precision of a battleship commander: A guide

I have a simple HTML table that I want to parse line by line using JavaScript without any specific identifiers like class names. My goal is to create a mapping system similar to the following: AC000(red)(green) => cell match. As illustrated in the scr ...

Utilizing jQuery to incorporate a radio input function in a POST request

When the Index.php page button is pressed, data is sent to the Resultx.php script page, which then responds with an asynchronous call back on the same Index.php page. index.php <script> $(document).ready(function() { $("#input_form").subm ...

The like button animation works perfectly for individual posts, but for multiple posts, only the like button on the first post

Having an issue with the like button code on a single news feed. The button works for the first post, but when clicking on other posts, it only affects the first post button. I am using post UI and looping the UI based on the total post count without Javas ...

Having trouble displaying options in VueJS Component using datalist

Currently, I am harnessing the power of VueJS and its components to create an extensive array of datalists and selectors, each equipped with a submit button for validation upon form submission. Initially, I successfully implemented a datalist within a com ...

Working with HTTPS in Angular: A guide to using $http

Can anyone provide guidance on how to handle https + cross-domain URL using $http? I managed to solve my issue using $.ajax, but I prefer using $http because I have an $http interceptor set up to automate certain processes. I've checked out related ...

The command `grunt.option('force', true) isn't functioning properly

After reviewing the grunt.options documentation, my initial expectation was that I could initiate a Grunt task programmatically with the force option activated in this manner: var grunt = require('grunt'); grunt.option('force', true); ...

What is the process for customizing the marker icon on a leaflet map using NUXT.js?

I'm currently in the process of changing the marker icon for individual markers on my OpenStreetMap. mapIconsReinit(L) { delete L.Icon.Default.prototype._getIconUrl; L.Icon.Default.imagePath = '' L.Icon.Default.mergeOptions({ ...

Sending various FormData instances to Node Express

I am facing a challenge where I need to submit three forms with just one click. The data collected from these forms should then create three separate rows in the database through an API, triggering a POST request. How can I effectively pass all this data ( ...

What is the method for obtaining the most up-to-date JSON GET request URL?

Using JQGrid with search filters and setting loadOnce=false. I perform a search in the grid and observe the JSON request URL in firebug: http://localhost:8080/myapp/items/listGrid?ticketId=&_search=true&nd=1393573713370&rows=20&page=1& ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

TypeScript generic types allow you to create reusable components that

function genericIdentity<T>(arg: T): T { return arg; } let myGenericIdentity: <U>(arg: U) => U = genericIdentity; I see that the 'genericIdentity' function is accepting an argument of a generic type. However, I am unsure about ...

Exploring the Potential of CSS Styling within Vue.js

I am in the process of creating a website and I am looking for a way to manage my styles through Vue. I want to be able to utilize CSS with Vue, as the style of .skill-bar serves as the background of the bar, while .skill-bar-fill represents the green fil ...

When an attempt to make a POST request using fetch() is made, a TypeError: Failed to fetch error is immediately thrown instead of

My front-end form is posting data using the fetch() function. Everything works fine and I get the correct response from the server when it runs smoothly without any interruptions. However, when I debug the server endpoint, it throws a TypeError: failed to ...

The module '@types/googlemaps/index.d.ts' cannot be found

I'm working on integrating the Google Maps API into my Angular project and ran into some issues. Here's what I did to install the necessary npm packages: npm install @agm/core --save-dev npm install @types/googlemaps --save-dev Next, I added th ...

Enhance the appearance of dynamically loaded JSON responses within prism.js using JavaScript

Is there a way to format a JSON response nicely after it has been loaded dynamically in prism ()? Currently, I am seeing the Json syntax highlighted all in one row: {"status":200,"success":true,"message":"Success! Rec ...

Typescript controller inheritance leading to Error: $injector:unpr Unknown Provider due to minification

LATEST UPDATE: 2019/07/16 The issue I am facing is actually a result of misusing $inject. Instead of declaring it as private $inject in api-service.ts, it should have been public static $inject = [...]. During the minification process, explicit injection ...

Stop the user from entering anything other than numbers

I am working on a directive to only allow users to input numbers. Check out my implementation below. Snippet from my directive template: <input type="text" maxlength="5" ng-keypress="allowNumbers($event)"> Function in my directive: $scope.allowNu ...

Issue encountered while serializing the `.product` object retrieved from the `getStaticProps` function in NextJS, in conjunction with

I ran into an error message saying "Error: Error serializing .product returned from getStaticProps in "/products/[id]". Reason: undefined cannot be serialized as JSON. Please use null or omit this value." This issue occurred while I was attempting to crea ...

Challenges arise when attempting to modify an ArrowHelper without creating a new instance

In my project using three.js, I am facing a challenge with updating the components of 3 ArrowHelper. Currently, I am able to update these 3 ArrowHelper in my animation by creating new instances each time the drawing function is called. For instance, in my ...

fixing errors with express, angularJS, and socket.io

I am currently in the process of setting up Socket.io on my website using ExpressJS and AngularJS NodeJS server.js var express = require('express'); var app = express(); fs = require('fs'); // specifying the port ...