目录
Webpack只对js进行打包;
以安装插件为主;
一:初始化项目
npm init
//查看初始化内容
npm init -y
二:安装打包工具
// 全局安装webpack
npm install webpack -g
// 把webpack和webpack-cli添加到依赖中去
npm install webpack webpack-cli --save-dev
三:创建项目
建一个html:index.html
建一个js: index.js
建一个css:index.css
文件解构如下:
css和js,我放在了static下面的,大家根据自己需求安排;node_modules是安装webpack自动生成的;
四:打包
1:先创建配置文件
config.js或者webpack.config.js;
2:package.json
{
"name": "webpack_ceshi",
"version": "1.0.0",
"description": "webpack测试",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack --config config.js"
},
"author": "小王",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "^5.3.2",
"webpack": "^5.42.1",
"webpack-cli": "^4.7.2"
}
}
package.json文件是可以配置的,比如你的打包命令可以在scripts中配置为,如下:
"start": "webpack --config config.js"
start,是自定义名称
安装html-webpack-plugin插件,
// html打包插件
npm install html-webpack-plugin --save-dev
const path = require("path")
var HtmlWebpackPlugin = require('html-webpack-plugin'); // 引入html打包插件
module.exports={
mode:"none", //development或者production开发模式,可设none
entry:{ // 打包入口 js
// 'dist/js/index':"./static/js/index.js"
},
output:{ // 输出(打包)
filename:'[name].[chunkHash:5].js', // 输出(打包)文件名称
path:path.resolve(__dirname,"dist") // 输出(打包)文件夹名称
},
// 插件配置的地方,plugins数组接收new实例
plugins:[
new HtmlWebpackPlugin({ // html插件
// chunks:['dist/js/index.js'],
filename:'index.html', // 打包后 html名称
template:'page/index.html' // 接收 打包的模板
})
]
}
打包:执行package.json里面配置的打包命令:npm run start,生成如下