本文主要介绍webpack的基本使用,通过简单的打包流程进行具体说明。
1.新建pack文件夹,运行npm init -y初始化package.json文件,不用-y则需要手动进行配置。
package.json文件内容如下:
{
"name": "pack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"jquery": "^3.6.0"
},
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.10.0"
}
}
2.新建src文件夹,新建index.html和index.js文件
3.安装jquery,书写index.js文件如下
import $ from 'jquery'
$(function() {
$('.btn').click(function() {
$('#showContent').slideDown();
$('#showContent').css('backgroundColor', 'yellow')
})
})
4.安装webpack和webpack-cli包,创建webpack.config.js文件,配置内容如下:
module.exports = {
mode: 'development',
devServer: {
open: true,
host: '127.0.0.1',
port: 8800,
static: './'
}
}
5.安装webpack-dev-server包,修改命令如下:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server"
},
6.index.html文件引入"/bundle.js"文件,运行npm run dev命令即可
7.上述文件运行后并不会直接打开首页,故需要进行配置。首先运行npm i html-webpack-plugin -D
命令,安装html-webpack-plugin包,配置预览页面。在webpack.config.js中的具体配置如下:
const HtmlWebpack = require('html-webpack-plugin')
const h = new HtmlWebpack({
template: './src/index.html',
filename: 'index.html'
})
module.exports = {
mode: 'development',
devServer: {
open: true,
host: '127.0.0.1',
port: 8800,
static: './'
},
plugins: [h]
}
8.在package.json文件中定义如下内容
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server",
"build": "webpack"
}
运行npm run build命令即可对文件进行打包,会生成dist这一最终的文件夹。
9.可进行项目入口与出口文件的配置。默认入口文件是src目录下的index.js文件,出口文件是main.js,现配置为bundle.js.需要使用npm内置的path包,完整代码如下:
const HtmlWebpack = require('html-webpack-plugin')
const path = require('path')
const h = new HtmlWebpack({
template: './src/index.html',
filename: 'index.html'
})
module.exports = {
mode: 'development',
devServer: {
open: true,
host: '127.0.0.1',
port: 8800,
static: './'
},
plugins: [h],
entry: path.join(__dirname, './src/index.js'),
output: {
path: path.join(__dirname, './dist'),
filename: 'bundle.js'
}
}