提取码:jxmx
模块包括:
1)加载器:babel-loader、css-loader、style-loader、url-loader
2)插件:html-webpack-plugin、mini-css-extract-plugin
3)热替换:webpack-dev-server。
可进行基本的js、css、html、图片的打包。
package.json
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.4.4",
"@babel/preset-env": "^7.4.4",
"babel-loader": "^8.0.6",
"css-loader": "^2.1.1",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.6.0",
"style-loader": "^0.23.1",
"url-loader": "^1.1.2",
"webpack": "^4.31.0",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.3.1"
}
}
webpack.config.js
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); //引入"mini-css-extract-plugin",打包时分离css文件
const HtmlWebpackPlugin = require('html-webpack-plugin'); //引入"html-webpack-plugin",打包HTML文件
module.exports = {
mode: 'development',
devServer: {//可进行热替换
contentBase: path.join(__dirname, 'dist'),
compress: false,//是否压缩
port: 8088
},
entry: {
main: './src/main.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js' //生成多个对应的打包的js文件,name对应entry中的k-v中的key值
},
module: {
rules: [
//bable-loader 转码器
{
test: /\.m?js$/, //正则
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-proposal-object-rest-spread'] //添加支持的插件,如支持React语法规则,注意:正则需要扩展文件的扩展名
}
}
},
//css-loader 处理css
{
test: /\.css$/,
use: [
// "style-loader", // creates style nodes from JS strings
MiniCssExtractPlugin.loader,
"css-loader", // translates CSS into CommonJS
// "sass-loader" // compiles Sass to CSS, using Node Sass by default]
]
},
{//url-loader 处理图片
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader?limit=10000&name=imgs/[name].[ext]',
}
]
},
]
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'css/[name].css',
chunkFilename: '[id].css',
}),
new HtmlWebpackPlugin({
title: 'Good Morning',//title可以应用到html文件中
filename: 'index.html',//输出文件
template: 'index.html'//自己的输入文件
})
]
};
ReadMe.txt
npm install
npm run build
npm run start
打开网页:localhost:8088/