Welcome to the Comprehensive Guide on ts-loader
ts-loader is a TypeScript loader for Webpack. It merges the power of TypeScript and the robustness of Webpack, ensuring a seamless development experience for developers. This guide introduces ts-loader
and demonstrates several useful APIs with code snippets.
Installation
npm install ts-loader typescript --save-dev
Basic Setup
To get started, configure webpack.config.js
as shown below:
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
API Examples
1. TranspileOnly Mode
Use this mode to speed up compilation:
module: {
rules: [
{
test: /\.ts$/,
use: {
loader: 'ts-loader',
options: {
transpileOnly: true,
},
},
exclude: /node_modules/,
},
],
},
2. HappyPack Mode
Enable multi-threaded compilation:
const HappyPack = require('happypack');
module: {
rules: [
{
test: /\.ts$/,
use: [
{
loader: 'happypack/loader',
options: {
id: 'ts',
},
},
],
exclude: /node_modules/,
},
],
},
plugins: [
new HappyPack({
id: 'ts',
loaders: ['ts-loader'],
}),
],
3. Project References
Use TypeScript Project References for more optimized builds:
module: {
rules: [
{
test: /\.ts$/,
use: {
loader: 'ts-loader',
options: {
projectReferences: true,
},
},
exclude: /node_modules/,
},
],
},
Application Example
Here’s a simple example of a Webpack setup using ts-loader:
// src/index.ts
import { add } from './math';
console.log(add(2, 3));
// src/math.ts
export const add = (a: number, b: number): number => a + b;
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
With this setup, you can begin leveraging the power of TypeScript with Webpack using ts-loader.
Hash: 74c2554eb01ccb9346be56dde520f9506122c685f27163e81fe89d251ba6fd98