隐藏侧边栏

什么是webpack

  • 一、webpack是什么

    webpack 是一个用于现代 JavaScript 应用程序的静态模块化打包构建工具

    模块化:服务端Common.js(module.exports,require),浏览器端ES Module(export,export default,import {} from xxx)

    src目录 你写的源代码

    

  npm run build

  dist--index.html,js css

 

  • 二、webpack快速使用

    2.1 初始化package.json

   

 npm init -y

 


    2.2 安装webpack相关依赖

   

 npm i webpack webpack-cli -D

 

  • 2.3 写一点点测试代码   
 src index.js,tools.js

 public index.html 引入dist/main.js

 

  • 2.4 在package.json中添加打包脚本
{
....
"scripts": {
"build":"webpack"
},
...
}

 

  • 2.5 编写webpack配置文件
编写webpack配置文件,让webpack实现灵活环境定制,如下:

//引入相关依赖
const webpack = require('webpack')
const path=require('path')
​
//创建一个webpak配置对象
const config = {
//设置模式
mode:'development',
//配置入口
entry:'./src/main.js',
//配置出口
output: {
//打包路径
path:path.resolve(__dirname,'dist'),
//打包文件名 
filename: 'js/bundle.js',
//清理无用文件
clean:true

}
}
​
​
//抛出对象
module.exports=config

 

  • 2.6 安装webpack服务器
安装webpack-dev-server: npm i webpack-dev-server -D

配置webpack.config.js

{
....
​
//配置webpack服务器
devServer: {
port: 9999,
//静态目录位置
static: {
directory:'dist'
}
}
....
}
配置package.json运行脚本

{
...
"scripts": {
"build": "webpack",
"serve": "webpack serve"
},
...
}

 

  • 2.7 自动注入html
安装html-webpack-plugin: npm i html-webpack-plugin -D

配置webpack.config.js

//引入相关依赖
const webpack = require('webpack')
const path = require('path')
//引入html-webpack-plugin
const HtmlWebpackPluin=require('html-webpack-plugin')
​
//创建一个webpak配置对象
const config = {
//设置模式
mode:'development',
//配置入口
entry:'./src/main.js',
//配置出口
output: {
//打包路径
path:path.resolve(__dirname,'dist'),
//打包文件名 
filename: 'js/bundle[contenthash].js',
//清理无用文件
clean:true

},
//配置插件
plugins: [
new HtmlWebpackPluin({
//从哪个模板生成html
template:'./public/index.html',
//生成后的html文件名
filename:'index.html'
})
],
//sl
//配置webpack服务器
devServer: {
port: 9999,
//静态目录位置
static: {
directory:'dist'
}
}
}
​
​
//抛出对象
module.exports=config

 

posted @ 2023-01-14 13:57  阴茵  阅读(121)  评论(0编辑  收藏  举报