At first, I wonder why Babel supports TypeScript.
And I can't imagine how to use TypeScript within Babel.
This article explains how I use TypeScript within Babel and Webpack.
TLDR
See this webpack.config.js
:
module.exports = { resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] }, module: { rules: [ { test: [/\.jsx?$/, /\.tsx?$/], use: 'babel-loader', exclude: /node_modules/ } ] } }
Use babel-loader
to /\.tsx?$/
same as /\.jsx?$/
?!
Yes, babel-loader
. I explain how to acheive this step by step.
How it works?
So simple.
Thanks to @babel/preset-typescript
, we can handle /\.tsx?$/
by babel-loader
.
See .babelrc
below:
{ "presets": [ "@babel/typescript" ], "plugins": [ "@babel/proposal-class-properties", "@babel/proposal-object-rest-spread" ] }
Demo
saltyshiomix / webpack-typescript-react-starter
Webpack + TypeScript + React = ❤️
Webpack + TypeScript + React = ❤️
As of Babel v7, now we can handle .ts
or .tsx
files same as .js
or .jsx
files like this:
// webpack.config.js module.exports = { resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'], }, module: { rules: [ { test: [/\.jsx?$/, /\.tsx?$/], use: 'babel-loader', exclude: /node_modules/, }, ], }, }
Use babel-loader
to /\.tsx?$/
?!
Yes, babel-loader
. See .babelrc
:
Thanks to @babel/preset-typescript
, we can handle /\.tsx?$/
files same as /\.jsx?$/
files :)
package.json is so simple and so you can imagine how to use:
{ "name": "babel-typescript-react-boilerplate", "scripts": { "check-types": "tsc", "start": "webpack-dev-server --mode development" }, "dependencies": { "react": "^16.6.3", "react-dom": "^16.6.3" }, "devDependencies": { "@babel/core": "^7.1.6", "@babel/plugin-proposal-class-properties": "^7.1.0", "@babel/plugin-proposal-object-rest-spread": "^7.0.0", "@babel/preset-env": "^7.1.6", "@babel/preset-react": "^7.0.0", "@babel/preset-typescript": "^7.1.0", "@types/react": "^16.7.6", "@types/react-dom": "^16.0.9", "babel-loader": "^8.0.4", "html-webpack-plugin": "^3.2.0", "typescript": "^3.1.6", "webpack": "^4.25.1", "webpack-cli": "^3.1.2", "webpack-dev-server": "^3.1.10" } }
Conclusion
Before bable@7
, we need to webpack JavaScript files by babel-loader
and TypeScript files by ts-loader
or awesome-typescript-loader
.
Therefore a setting file webpack.config.js
is sometimes so complex and hard to maintenance.
TypeScript with Babel makes it easier and provides us better development experience :)
Top comments (2)
Thank you, its a nice post. Here is my boilerplate github.com/auvansang/rtw
It's works fine. Thanks!