![]()
When Webpack isn’t properly transpiling modern JavaScript (ES6+) or JSX, it’s typically a configuration issue. Here’s how to resolve it:
Core Solution: Proper Babel + Webpack Setup
1. Install Required Dependencies
npm install --save-dev \
@babel/core \
@babel/preset-env \
@babel/preset-react \
babel-loader \
webpack \
webpack-cli
2. Create/Update Webpack Configuration (webpack.config.js)
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env', {
targets: "> 0.25%, not dead",
useBuiltIns: 'usage',
corejs: 3
}],
'@babel/preset-react'
]
}
}
}
]
},
resolve: {
extensions: ['.js', '.jsx']
}
};
3. Create Babel Configuration (.babelrc or babel.config.js)
{
"presets": [
["@babel/preset-env", {
"targets": {
"browsers": [">0.25%", "not dead"]
},
"useBuiltIns": "usage",
"corejs": 3
}],
"@babel/preset-react"
]
}
Common Issues and Fixes
1. JSX Not Transpiling
Symptoms: Unexpected token errors on < or >
Solution:
- Ensure
@babel/preset-reactis installed and in presets - Verify files have
.jsxextension or are included in the test regex
2. Async/Await Not Working
Solution:
npm install @babel/plugin-transform-runtime --save-dev
Then add to Babel config:
{
"plugins": [
["@babel/plugin-transform-runtime", {
"regenerator": true
}]
]
}
3. ES6+ Features in node_modules
Solution: Update Webpack rule:
{
test: /\.js$/,
exclude: /node_modules\/(?!(your-module|another-module)\/).*/,
use: {
loader: 'babel-loader'
}
}
Advanced Configuration
For TypeScript
- Install dependencies:
npm install --save-dev \
@babel/preset-typescript \
typescript \
@types/react \
@types/react-dom
- Update Webpack config:
{
test: /\.(ts|tsx)$/,
use: 'babel-loader'
}
- Update Babel config:
{
"presets": [
"@babel/preset-typescript",
// ... other presets
]
}
For CSS/SCSS
Add to Webpack config:
{
test: /\.(css|scss)$/,
use: ['style-loader', 'css-loader', 'sass-loader']
}
Verification Steps
- Check your build output contains transpiled code
- Look for any Webpack warnings during build
- Test in target browsers
- Use
npx webpack --stats verbosefor detailed analysis
Optimization Tips
- Split configurations for development/production
- Add cache to Babel loader:
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true
}
}
- Use thread-loader for faster builds in production
