🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
``` npm i babel-loader @babel/core @babel/preset-env -D ``` polyfill 不推荐,一般用corejs代替 ``` npm i @babel/core @babel/polyfill -D ``` ``` npm i core-js -D ``` webpack.config.js ``` const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/js/index.js', output: { filename: 'js/built.js', path: resolve(__dirname, 'build') }, module: { rules: [ /* js兼容性处理:babel-loader @babel/core 1. 基本js兼容性处理 --> @babel/preset-env 问题:只能转换基本语法,如promise高级语法不能转换 2. 全部js兼容性处理 --> @babel/polyfill 问题:我只要解决部分兼容性问题,但是将所有兼容性代码全部引入,体积太大了~ 3. 需要做兼容性处理的就做:按需加载 --> core-js */ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { // 预设:指示babel做怎么样的兼容性处理 presets: [ [ '@babel/preset-env', { // 按需加载 useBuiltIns: 'usage', // 指定core-js版本 corejs: { version: 3 }, // 指定兼容性做到哪个版本浏览器 targets: { chrome: '60', firefox: '60', ie: '9', safari: '10', edge: '17' } } ] ] } } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ], mode: 'development' }; ``` src/index.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>webpack</title> </head> <body> <h1>hello webpack</h1> </body> </html> ``` src/js/index.js ``` // import '@babel/polyfill'; const add = (x, y) => { return x + y; }; console.log(add(2, 5)); const promise = new Promise(resolve => { setTimeout(() => { console.log('定时器执行完了~'); resolve(); }, 1000); }); console.log(promise); ```