1、创建项目
执行npm init -y,初始化包管理配置文件package.json
2、新建src源代码目录,新建src/index.html和src/index.js脚本文件
3、npm install jquery -S
4、index.js
//使用ES6导入语法
import $ from 'jquery'
$(function(){
$('li:odd').css('background-color','pink')
})
在index.html中引用index.js <script src='./index.js'></script>
5、安装webpack
npm install webpack@5.42.1 webpack-cli@4.7.2 -D
6、项目配置webpack
①在项目根目录中,创建名webpack.config.js的webpack配置文件,并初始化如下的基本配置:
const path=require('path')
module.exports = {
entry:{
index:path.join(__dirname, './src/index.js')
},
output:{
filename:'main.js',
path:path.resolve(__dirname,'./dist')
},
mode: 'development' //mode用来指定构建模式。可选值有development 和 production(会压缩打包文件)
}
②在package.json 的 scripts节点下,新增dev脚本如下:
"scripts" : {
"dev" : "webpack" //script节点下的脚本,可以通过npm run 执行。例如npm run dev
}
③在终端中运行npm run dev命令,启动webpack进行项目的打包构建
7、引用dist下js
在index.html中引用index.js <script src='../dist/main.js'></script>
8、webpack插件
① webpack-dev-server,修改源代码不需要每次重新npm run dev
npm install webpack-dev-server@3.11.2 -D
修改package.json -> scripts 中的dev命令如下:
"scripts": {
"dev" :"webpack serve",//script节点下的脚本,可以通过 npm run 执行
}
再次运行npm run dev命令,重新进行项目的打包
在浏览器中访问http://localhost:8080地址,查看自动打包效果
在index.html中引用index.js <script src='/main.js'></script> 读取内存中的main.js
②html-webpack-plugin 复制src/index.html到根目录,方便访问http://localhost:8080地址时不再次点击src目录
npm install html-webpack-plugin@5.3.2 -D
//导入 html-webpack-plugin这个插件,得到插件的构造函数
const HtmlPlugin = require('html-webpack-plugin')
//new构造函数,创建插件的实例对象
const htmlPlugin = new HtmlPlugin({
//指定要复制哪个页面
template: '.isrc/index.html ',
//指定复制出来的文件名和存放路径
filename: './index.html'
})
//在moudle.exports中加入
plugins: [htmlPlugin]
//在moudle.exports中加入
devServer: {
//首次打包成功后,自动打开浏览器
open: true,
port: 8080,
//指定运行的主机地址
host:'127.0.0.1'
}
8、webpack的loader