2018-04-23 webpack入门
2018-04-23 本文已影响0人
彭奕泽
1. 初体验
很乱,数不清的配置
2. 安装
- 创建目录
mkdir webpack-demo
cd webpack-demo
npm init //创建一个package.json
- copy Github上webpack官网的文档
//这是webpack3,安装需要加@3
npm i webpack@3
//配置
touch webpack.config.js
vi webpack.config.js
//在里面写以下内容
/*
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};*/
//创建文件
touch src/index.js
//运行webpack
npx webpack //这时会多出dist目录,里面有bundle.js文件
3. 使用
- 在index.js里写
console.log(1)
//再运行webpack:
npx webpack
//再看bundle.js,这时会多出来一行console.log(1)
- 安装babel-loader自动转换es6,我用的是 7.x branch for docs with Babel v6
//安装v6,命令行
npm install babel-loader babel-core babel-preset-env webpack
//将这个复制到webpack的配置文件webpack.config.js里,加在output的下面
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
}
//加在output的下面,复制完后成这样
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
}
};
运行npx webpack
若出现can't find '...'
或can't resolve '...'
的报错,则安装省略号里的东西npm i '省略号'
注意:若是Couldn't find preset "env"
,不要安装env,而是npm i babel-preset-env
- 使用babel
//当你在写index.js里写
let a=1
//它就会帮你自动转换成es5了
3. 总结
太乱了太多配置了,希望parcel赶快升级替换掉webpack