- npm init -y 生成packge.json。
- npm i webpack webpack-cli -D,这时候能够npx webpack打包。
- packge.json文件script中退出
"dev": "webpack --config webpack.config.js"
新建webpack.config.js
const path = require("path"); // webpack外部办法path组件module.exports = { entry: "./main.js", // 入口文件指定 output: { //进口文件配置 配置进口打包门路 filename: "index.js", //打包后的文件名称 path: path.resolve(__dirname, "dist") //resolve绝对路径引入 }};
配置完这2个文件就能够间接 npm run dev打包了
4.打包时主动生成index.html
npm i -D html-webpack-plugin
webpack.config.js中退出
// index.html生成插件const HtmlWebPackPlugin = require("html-webpack-plugin"); module.exports = { plugins: [ new HtmlWebPackPlugin({ filename: "index.html", // 生成打包文件名 template: "./index.html", // 模板门路 minify: { //生产模式能够进行配置 removeAttributeQuotes: true, //删除 html文件双引号 collapseWhitespace: true //折叠控行 }, hash:true, //增加哈希值~~~~ }) ],}
5.css模块,css以行内的形式插入到head中
npm i -D --save css-loader style-loader
webpack.config.js中退出
module.exports = { module: { rules: [ { test: /.css$/, use: ["style-loader", "css-loader"] // 执行程序右->左,下->上 } ] }}
6.css抽离,css以link标签形式插入到head里
npm i -D --save mini-css-extract-plugin
const MinCssExtractPlugin = require("mini-css-extract-plugin"); // css抽离插件module.exports = { plugins: [ new MinCssExtractPlugin({ filename: "index.css", }) ], module: { rules: [ { test: /.css$/, use: [ MinCssExtractPlugin.loader, "css-loader" ] // 执行程序右->左,下->上 } ] }}
7.打包图片
css背景图
npm i -D url-loader
webpack.config.js中退出
module.exports = { module: { rules: [ { test: /.(png|svg|jpg|gif)$/, use: [ loader: 'url-loader?limit=8192&name=images/[hash:8].[name].[ext]', ] }, ] }}
js
main.js中退出
import vue from './src/img/vue.png'window.onload = function(){ var root = document.getElementById('root'); var image = new Image(); // 创立img标签 image.src = vue; // 将img的src属性设置成咱们引入的图片 root.append(image);}
html
npm i -D html-withimg-loader
webpack.config.js中退出
module.exports = { module: { rules: [ { test: /.(html|htm)$/i, use: ['html-withimg-loader'] // 解析html中的图片资源 }, { test: /.(png|svg|jpg|gif)$/, use: [ loader: 'url-loader, options: { esModule: false } ] }, ] }}