webpack 能够看作是模块打包机, 主要能够作到以下内容css
目的就是工程化,解放生产力html
npm install webpack webpack-cli -D
复制代码
const path=require('path');
module.exports={
mode: ''develepment, // 配置打包环境
entry: './src/index.js', // 配置入口
output: { // 配置出口
path: path.resolve(__dirname,'dist'),
filename:'bundle.js'
},
module: {}, // 配置模块 loaders
plugins: [], // 配置插件
devServer: {}, // 配置开发服务器}
复制代码
分为两个环境,开发环境(develepment)、生产环境(production)node
production 相比 develepment, 会在打包是作不少优化。工做中除上线外都用 develepmentreact
先用最简单的举例,单入口单出口webpack
const path = require('path'); //node系统模块
module.exports={
//入口配置
entry: './src/index.js',
//出口配置
output:{
path:path.resolve(__dirname,'dist'), //path必须是绝对路径
filename:'bundle.js'
}
};
复制代码
entry 入口能够使用相对路径,可是output.path 必须使用绝对路径web
entry 能够是 字符串'./src/index.js'
、数组 ['./src/index.js']
、对象 {a: './src/index.js'}
npm
若是想出口文件名中包含入口文件名的变量,能够使用 [name].js
数组
多入口文件浏览器
const path = require('path');
module.exports = {
entry:['./src/index.js','./src/index2.js'], //按照顺一块儿打包 bundle.js
output:{
path:path.resolve(__dirname, 'dist'),
filename:'bundle.js'
}
};
复制代码
多入口多出口配置服务器
const path = require('path');
module.exports = {
entry:{
index:'./src/index.js',
index2:'./src/index2.js'
},
output:{
path:path.resolve(__dirname, 'dist'),
filename:'[name].bundle.js'
}
};
复制代码
安装
npm i webpack-dev-server –D
复制代码
配置 webpack.config.js
devServer:{
contentBase:path.resolve(__dirname,'dist'),
host:'localhost', compress:true,
port:8080
}
复制代码
安装 html-webpack-plugin 配置模版
npm i html-webpack-plugin -D
复制代码
引入
const HtmlWebpackPlugin = require('html-webpack-plugin')
复制代码
使用
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html', // 模版地址
})
],
复制代码
// 第一种
use:['xxx-loader','xxx-loader']
// 第二种
loader:['xxx-loader','xxx-loader']
// 第三种
use:[{loader:'style-loader'},{loader:'css-loader'}]
复制代码
安装使用 style-loader css-loader
npm i style-loader css-loader -D
复制代码
配置
module:{
rules:[
{
test:/\.css$/,
use:['style-loader','css-loader']
}
]
}
复制代码
使用 babel 来编译 js
举例编辑 react 项目
安装使用 babel-loader @babel/core @babel/preset-env @babel/preset-react
npm i babel-loader @babel/core @babel/preset-env @babel/preset-react -D
复制代码
配置
module: {
rules: [
{test: /\.js$/, use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
}
}}
],
},
复制代码
安装使用 file-loader url-loader
cnpm i file-loader url-loader -D
复制代码
配置
{
test:/\.(png|jpg|gif)$/,
use:[{
loader:'url-loader',
options:{
limit:50,
outputPath:'images'
}
}]
}
复制代码
安装使用 copy-webpack-plugin
npm i copy-webpack-plugin -D
复制代码
引入
const CopyWebpackPlugin = require('copy-webpack-plugin');
复制代码
使用
plugins:[
new CopyWebpackPlugin([{
from:path.resolve(__dirname, 'src/assets'),
to:'./public'
}])
]
复制代码