webpack
唯一功能:打包
loader,没有loader,webpack只能打包js,有了loader,可以打包各种各样的文件,css,图片,视频,等等等等
webpack.config.js
module.exprts = {
model: 'none', 'production', 'development'',/*原样,productio:能压多大就压多小,development:保留关键位置*/
entry: '入口',
output: {
path,
filename
}
};
单入口
entry只有一个文件
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/js/1.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.min.js'
}
}
多入口
多入口编译速度变慢(不影响)
entry有多个
const path = require('path');
module.exports = {
mode: 'development',
entry: {
index: './src/js/1.js',
admin: './src/js/2.js'
},
output: {
path: path.resolve(__dirname, 'build'),
filename: '[name].min.js'
}
loader
没有loader,webpack就是废物,所以loader很重要
加载css
css-loader:加载css文件,读成字符串,style-loader:编译成css标签
顺序很重要,从后到前,先css-loader,再style-loader,顺序不对会报错
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/js/1.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.min.js'
},
module: {//模块
rules: [//规则
{test:/\.css$/,use:['style-loader','css-loader']}//test符合某个规则,use哪个模块
]
}
}
处理css
postcss-loader
autoprefixer[(加前缀)(插件[用来补webpack没有的功能])]
rules:[
{test:/\.css$/,use['style-loader','cssloader','postcss-loader']}
]
./postcss.config.js
module.exports={
plugins: [
require('autoprefixer')//加前缀
]
}
image.png
文件
file-loader
读取并输出文件
url-loader
rules: [{
test: /\.(png|gif|jpg)$/i,
use: {
loader: 'file-loader',
options: {
outputPath: 'images/'
}
}
}]
读取并输出base64
一般用于小图标
一个loader两用
rules: [{
test: /\.(png|jpg|gif)$/i,
use: {
loader: 'url-loader',
options: {
outputPath: 'images/',
limit: 32 * 1024
}
}
}]
如果文件小于32k,就使用url-loader,否则使用file-loader
less
less不需要postcss-loader和autoprefixer,它已经包括了
npm i less-loader less
./src/less/1.less
@b: #f00;
#div2 {
border: 1px solid @b
}
.src/js/1.js
import ../less/1.less
编译ES6
npm i babel-loader @babel/core @babel/preset-env -D
{
test: /\.jsx?/i,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
保留原来的es6代码
,
devtoll: 'source-map'
热更新
npm i webpack webpack-cli webpack-dev-server -D
./package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server"
},
npm run start
用localhost:8080去访问
npm run start
代码质量管理
eslint
./.eslintrc
{
"parseOptions:{
"ecmaVersion":6,//ES版本
"sourceType":"module",
"ecmaTeatures":{
"jsx":true
}
},
"rules":{
"indent":["error",2],//首行空两格,如果不是会报错
"linebreak-style":["error","windows"],//换行
"quotes":["error","double"],//双引号,单引号会报错
"semi":["error","always"]//结尾分号
}
}
package.json
{
test: /\.jsx?/i,
exclude: /node_modules/,
use: {
loader: 'eslint-loader',
options: {
}
}
}
单元测试
jest
npm i jest jest-webpack
./package.json
"scripts":{
"test":"jest-webpack",
}
./tests/1.test.js
const mod=require('../src/1')
test('fab 7',()=>{
expect(mod.fab(7).toBe(13))
})
npm run test
网友评论