webpack官网链接https://www.webpackjs.com
全局安装webpack
npm i webpack webpack-cli -g
npm init
接下来按照提示回车就可
开发局部安装
npm i webpack webpack-cli -d
配置webpack
-
新建一个webpack.config.js,将package.json中的scripts下的"build":“webpack"改为"build”:“webpack --mode production --config webpack.config.js”.
-
在src下新建一个index.js文件,新建public/index.html,新建index.css,自行写样式等测试即可
-
配置webpack的entry指向src/index.js,配置output,配置插件html-webpack-plugin处理html,配置安装插件css-loader和min-css-extract-plugin,插件安装npm i 插件名 -g
webpack.config.js代码如下
const path = require('path') const HtmlWebpackPlugin = reqiure("html-webpack-plugin") const MinCssExtractPlugin = require("min-css-extract-plugin") module.export = { entry: { index: './src/index.js' }, output: { path: path.resolve(process.cwd(), "dist"), //打包后文件位置 filename: '[name].[chunkHash].js' //打包后文件+hash值 }, module: { rules: [{ //配置css test: /\.css$/, use: [ MinCssExtractPlugin, 'css-loader' ] }] }. plugins: [ new HtmlWebpackPlugin({ //配置html title: 'webpack', //可在html中获取 template: 'public/index.html' }), new MinCssExtractPlugin({ filename: '[name].[chunkHash].css' }) ] }
配置webpack开发环境
webpack.config.js中配置deserver:
const path = require('path')
const HtmlWebpackPlugin = reqiure("html-webpack-plugin")
const MinCssExtractPlugin = require("min-css-extract-plugin")
module.export = {
entry: {
index: './src/index.js'
},
output: {
path: path.resolve(process.cwd(), "dist"), //打包后文件位置
filename: '[name].[chunkHash].js' //打包后文件+hash值
},
module: {
rules: [{ //配置css
test: /\.css$/,
use: [
MinCssExtractPlugin,
'css-loader'
]
}]
}.
plugins: [
new HtmlWebpackPlugin({ //配置html
title: 'webpack', //可在html中获取
template: 'public/index.html'
}),
new MinCssExtractPlugin({
filename: '[name].[chunkHash].css'
})
],
devServer: {
port: 3000, //开发环境下,服务端口3000
open:true //开发环境自动打开,还可配置其他
}
}