I'm bundling with webpack and normally I use ts-loader for ts files and babel for js
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}But I've noticed a lot of tutorial use babel-loader for both and just adding @babel/preset-typescript to .babelrc
{
test: /\(.jsx?|.tsx?)$/,
use: 'babel-loader',
exclude: /node_modules/
},
//.babelrc
plugins: ["@babel/preset-env", "@babel/preset-typescript"]Do y'all go for approach #1, #2 or something else entirely?
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.
typescript - Why use babel-loader with ts-loader? - Stack Overflow
reactjs - Webpack and babel-loader not resolving `ts` and `tsx` modules - Stack Overflow
Inconsistency with TypeScript in Module Resolution with Fully-Specified ESM Imports
Babel-loader with “@babel/preset-typescript” can not transform the git submodule tsx file?
» npm install ts-loader