πŸ”§ Error Fixes
Β· 1 min read

Webpack Loader Error β€” How to Fix It


Module parse failed: Unexpected token
You may need an appropriate loader to handle this file type.

Webpack encountered a file type it doesn’t know how to process. You need to add a loader for it.

Fix 1: Missing CSS Loader

# ❌ Importing CSS without a loader
import './styles.css';  // πŸ’₯

# βœ… Install CSS loaders
npm install -D css-loader style-loader

# webpack.config.js
module: {
    rules: [
        { test: /\.css$/, use: ['style-loader', 'css-loader'] },
    ],
}

Fix 2: Missing Babel/TypeScript Loader

# ❌ JSX/TSX without a transpiler
npm install -D babel-loader @babel/core @babel/preset-react

# webpack.config.js
{
    test: /\.(js|jsx|ts|tsx)$/,
    exclude: /node_modules/,
    use: 'babel-loader',
}

Fix 3: Image/Font Files

# ❌ Importing images without asset handling
import logo from './logo.png';  // πŸ’₯

# βœ… Webpack 5 β€” use asset modules (no extra loader)
{
    test: /\.(png|jpg|gif|svg|woff|woff2)$/,
    type: 'asset/resource',
}

Fix 4: SCSS/Sass

npm install -D sass sass-loader css-loader style-loader

# webpack.config.js
{
    test: /\.scss$/,
    use: ['style-loader', 'css-loader', 'sass-loader'],
}

Fix 5: Loader Order Matters

// ❌ Wrong order β€” loaders run right to left
use: ['css-loader', 'style-loader']  // πŸ’₯

// βœ… Correct order: style-loader wraps css-loader output
use: ['style-loader', 'css-loader']

Fix 6: node_modules Need Processing

// ❌ Excluding all node_modules
{ test: /\.js$/, exclude: /node_modules/, use: 'babel-loader' }

// Some packages ship untranspiled ESM
// βœ… Include specific packages
{
    test: /\.js$/,
    exclude: /node_modules\/(?!(problem-package)\/).*/,
    use: 'babel-loader',
}