使用Webpack 4.7.x版本仍需配置babel-loader吗?
Great question! Let's break this down step by step:
Why your ES6 code worked without babel-loader?
First off, it's important to clarify: Webpack 4 itself doesn't automatically transpile ES6+ syntax to ES5. Its core job is module bundling, not syntax transformation. The reason your code ran fine without babel-loader is likely one of these scenarios:
- You're targeting modern browsers that natively support all the ES6 features you're using (like
const,let, arrow functions, etc.). - Your project has another transpilation step set up elsewhere (e.g., a script using
@babel/clithat runs before Webpack, or a hidden plugin that handles transpiling under the hood).
The peer dependency warning with babel-loader@7.1.4
That warning is totally expected—babel-loader@7.x is tied to the Babel 6 ecosystem, and it explicitly requires babel-core@6 as a peer dependency. Peer dependencies are packages the loader expects to exist in your project but doesn't install on its own, so you'd need to add babel-core@6 to your devDependencies if you want to stick with this specific loader version.
Should you add babel-loader and babel-core to your project?
This boils down to your browser support requirements:
- If you need to support older browsers (like IE11, Chrome < 60, Firefox < 55, etc.): Yes, you absolutely need Babel to transpile ES6+ syntax to ES5. However, instead of sticking with the older Babel 6 stack, I'd recommend upgrading to the Babel 7 ecosystem: use
babel-loader@8.xpaired with@babel/core(note the scoped package name—Babel 7 renamedbabel-coreto@babel/core). This version is more actively maintained, supports newer JavaScript features, and avoids many legacy compatibility headaches. - If you only target modern browsers: If all your users are on browsers that natively handle the ES6 features you're using, you can skip
babel-loaderentirely. Webpack will bundle your code as-is, and browsers will run it without issue.
Quick Babel 7 setup example (if you go this route)
If you decide to implement Babel, here's a minimal, up-to-date configuration:
- Install the required packages:
npm install --save-dev babel-loader @babel/core @babel/preset-env - Add a rule to your
webpack.config.js:module.exports = { // ... other Webpack config module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: 'babel-loader' } ] } }; - Create a
.babelrcfile in your project root to define presets:{ "presets": [ ["@babel/preset-env", { "targets": { "browsers": ["last 2 versions", "ie >= 11"] } }] ] }
内容的提问来源于stack exchange,提问作者codematix

