webpack使用babel基本配置
程序员文章站
2022-07-12 20:56:51
...
配置es6使用的babel
1. package.json文件
{
"name": "webpack_class",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"autoprefixer-loader": "^3.2.0",
"css-loader": "^0.28.4",
"file-loader": "^0.11.2",
"html-webpack-plugin": "^2.30.1",
"less": "^2.7.2",
"less-loader": "^4.0.5",
"style-loader": "^0.18.2",
"url-loader": "^0.5.9",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
},
"dependencies": {
"vue": "^2.4.2"
}
}
2. 装包
cnpm install babel-loader babel-core babel-preset-es2015 babel-plugin-transform-runtime -D
3. 配置webpack
const htmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path')
module.exports = {
entry:{ //main是默认入口,也可以是多入口
main:'./src/main.js'
},
//出口
output:{
filename:'./build.js', //指定js文件
path: path.join(__dirname,'dist') //最好是绝对路径
//代表当前目录的上一级的dist
},
module:{
//一样的功能rules: webpack2.x之后新加的
loaders:[ //require('./a.css||./a.js')
{test:/\.css$/,
loader:'style-loader!css-loader',
//顺序是反过来的2!1
},
{
test:/\.(jpg|svg|png|gif)$/,
loader:'url-loader?limit=4096&name=[name].[ext]',
//顺序是反过来的2!1
//[name].[ext]内置提供的,因为本身是先读这个文件
// options:{
// limit:4096,
// name:'[name].[ext]'
// }
},{//处理ES6的js
test:/\.js$/,
loader:'babel-loader',
//排除 node_modules下的所有
exclude:/node_modules/,
options:{
presets:['es2015'],//关键字
plugins:['transform-runtime'],//函数
}
}
]
},
plugins:[
//插件的执行顺序是依次执行的
new htmlWebpackPlugin({
template:'./src/index.html',
})
//将src下的template属性描述的文件根据当前配置的output.path,将文件移动到该目录
]
}
4. 在main.js中引入common.js
//commonjs引入cal对象
// var cal = require('./cal.js');
//es6的模块引入
import cal from './cal.js';
//获取按钮
document.getElementById('btn').onclick = function(){
var n1 = document.getElementById('n1').value - 0;
var n2 = document.getElementById('n2').value - 0;
var sum = cal.add(n1,n2);
document.getElementById('result').value = sum;
}
5. 在cal.js中导出
var cal = {
add:function(n1,n2){
return n1 + n2;
}
}
//commonjs导出
// module.exports = cal;
// ES6导出
export default cal;
附上index.html文件
<html>
<head>
<meta charset="UTF-8">
<title>01_模块化计算机</title>
</head>
<body>
<input type="text" name="" id="n1"> +
<input type="text" name="" id="n2">
<button id="btn">=</button>
<input type="text" name="" id="result">
</body>
</html>
下一篇: CUDA C