webpack4.29.x成神之路(十一) babel编译es6
栏目: JavaScript · 发布时间: 6年前
内容简介:上节:webpack-dev-server下上节目录如下:
上节:webpack-dev-server下
上节目录如下:
基本用法
es6语法因为浏览器兼容性问题较多,本不能直接使用,但因为babel这种能降级es6+语法的工具,使得es6+已提前普及。先来写点es6语法。
src/index.js:
const promise = new Promise(function(resolve) {
console.log('Promise');
resolve();
});
promise.then(function() {
console.log('resolved.');
});
然后npm run build, 打开ie浏览器(谷歌实在太先进鸟....):
明显IE不能完全失败es6语法,所以我们就需要将es6代码降级成es5甚至更低。
修改配置webpack.config.js:
// 省略依赖
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: '[name].js',
path: resolve(__dirname, 'bundles')
},
// 开启devServer
devServer: {},
module: {
rules: [{
test: /\.(gif|jpg|jpeg|png|svg)$/,
use: ['url-loader']
}, {
test: /\.less$/,
use: ['style-loader', 'css-loader', 'postcss-loader', 'less-loader']
}, {
test: /\.js$/,
// node_modules里的代码基本都是经过了编译的,所以忽略
exclude: /node_modules/,
loader: 'babel-loader'
}]
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html'
}),
new CleanWebpackPlugin()
]
};
根目录下新建babel.config.js:
const presets = [
["@babel/env"]
];
module.exports = { presets };
然后安装依赖:
npm i @babel/core @babel/preset-env babel-loader -D
重新npm run dev,刷新ie:
还是不行,这是因为:
- babel-loader只识别.js文件,
- @babel/preset-env才是编译语法
- preset-env只会转换语法,并不会转换API。 对于ES6的内建功能(如 Promise / Set / Map),原型链的扩展(Array / Object等)需要用垫片库(polyfill)来支持。
所以再安装:npm i @babel/polyfill -D
scr/index.js引入:
import "@babel/polyfill"; // 省略
再次npm run dev刷新ie:
这样就有效果了。
babel还有非常多的配置和插件,比如:
babel.config.js:
const presets = [
["@babel/env", {
// 设置打包后的代码将在哪些浏览器运行?只针它们做转化
targets: {
edge: "17",
firefox: "60",
chrome: "67",
safari: "11.1",
},
// 目前@babel/polyfill依赖的core-js@2,需要指定此选项并安装
corejs: 2,
/*
* @babel/polyfill会将所有高阶语法转化,配置useBuiltIns只转化项目中用到的语法
*797k => 291k
* 当useBuiltIns: "usage"时,入口文件就不需要import "@babel/polyfill"了
* 当useBuiltIns: "entry"时,需要在入口文件里import "@babel/polyfill"
* */
useBuiltIns: "usage"
}
]
];
module.exports = { presets };
本教程就不过多涉及了,最好的学习方式还是撸 官网文档
下节:source-map(待更新)
以上所述就是小编给大家介绍的《webpack4.29.x成神之路(十一) babel编译es6》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- Xcode 编译疾如风系列(二):并行编译
- 编写 MSBuild 内联编译任务(Task)用于获取当前编译环境下的所有编译目标(Target)
- 使用 Visual Studio 编译时,让错误一开始发生时就停止编译(以便及早排查编译错误节省时间)
- Go编译缓存导致C文件修改后未重新编译
- Android Apk反编译系列教程(一)如何反编译APK
- 漫话:如何给女朋友解释什么是编译与反编译
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
How to Solve It
Zbigniew Michalewicz、David B. Fogel / Springer / 2004-03-01 / USD 59.95
This book is the only source that provides comprehensive, current, and detailed information on problem solving using modern heuristics. It covers classic methods of optimization, including dynamic pro......一起来看看 《How to Solve It》 这本书的介绍吧!