How to setup TypeScript + Babel + Webpack?
(4,32): error TS2304: Cannot find name 'regeneratorRuntime'.
This is a symptom that the output of babel
is getting fed to ts
. This order is wrong
Fix
You compilation setup should have TS output fed to Babel.
Alternatively you can compile TypeScript with just Babel using @babel/preset-typescript
.
More
Compiling TypeScript with Babel : https://babeljs.io/docs/en/babel-preset-typescript
Babel 7 does not need ts-loader.
As of Babel 7 the ts-loader
is unnecessary, because Babel 7 understands TypeScript. Complete details of a TypeScript + Babel7 + Webpack setup are here.
An overview of the set up without ts-loader.
Install Babel's TypeScript support. Only @babel/preset-typescript
is mandatory; the other three add additional features that TypeScript supports.
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
Configure the additional .babelrc
plugins and presets.
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript"
],
"plugins": [
"@babel/proposal-class-properties",
"@babel/proposal-object-rest-spread"
]
}
And update your webpack.config.js
(other code is omitted for clarity).
module: {
rules: [
{
test: /\.(js|jsx|tsx|ts)$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx', '.tsx', '.ts'],
},
Loaders always execute right to left, so changing to
test: /\.tsx?$/, loaders: ['babel-loader', 'ts-loader'], exclude: /node_modules/
fixed the issue since it is going to run ts-loader
first.
Full 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/
}],
}
};
Sample project: brunolm/typescript-babel-webpack.