loader就是将除了js外的别的东西变成模块化,例如css、图片、es6转es5
webpack官网地址:https://www.webpackjs.com/
css打包
前往官网下载loader
npm install style-loader --save-dev
npm install --save-dev css-loader
//安装后webpack.config.js
{
module: {
rules: [
{
test: /\.css$/,
//别换顺序webpack从右向左读
use: [ 'style-loader', 'css-loader' ]
}
]
}
}
less打包
跟css差不多先下载->引入->配置
npm install --save-dev less-loader less
//安装后webpack.config.js
{
module: {
rules: [
{
test: /\.css$/,
//别换顺序webpack从右向左读
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.less$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "less-loader" // compiles Less to CSS
}]
}
]
}
}
图片打包
npm install --save-dev url-loader
//安装后webpack.config.js
{
module: {
rules: [
{
test: /\.css$/,
//别换顺序webpack从右向左读
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.less$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "less-loader" // compiles Less to CSS
}]
},
{
test: /\.(png|jpg|gif|jpeg)$/,
use: [
{
loader: 'url-loader',
options: {
//当加载的图片小于limit,会将图片编译成base64
//当大于limit需要file-loader进行加载
limit: 13000,
//img文件夹下,本身图片的名字.哈希.拓展名=打包后的图片名
name:'img/[name].[hash:8].[ext]'
},
}
]
}
]
}
}
ES6语法处理
//千万注意版本问题
npm install babel-loader babel-core babel-preset-env webpack
//安装后webpack.config.js
{
module: {
rules: [
{
test: /\.css$/,
//别换顺序webpack从右向左读
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.less$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "less-loader" // compiles Less to CSS
}]
},
{
test: /\.(png|jpg|gif|jpeg)$/,
use: [
{
loader: 'url-loader',
options: {
//当加载的图片小于limit,会将图片编译成base64
//当大于limit需要file-loader进行加载
limit: 13000,
//img文件夹下,本身图片的名字.哈希.拓展名=打包后的图片名
name:'img/[name].[hash:8].[ext]'
},
}
]
},
{
test: /\.js$/,
//exclude排除
//include包含
exclude: /(node_modules|bower_components)/,//目的是让他就扫描src就可以了
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
]
}
}