一、初始化项目
默认系统已经安装node
//初始化
pnpm init//安装webpack
pnpm i -D webpack webpack-cli
新建一个index.html的入口文件
新建一个src文件存放js代码,src里面新建一个index.js
package.josn配置打包命令
{"name": "webpack-cs","version": "1.0.0","description": "","main": "index.js","scripts": {"build": "webpack"},"keywords": [],"author": "","license": "ISC","devDependencies": {"webpack": "^5.89.0","webpack-cli": "^5.1.4"}
}
然后命令行输入 npm run build,就会默认生成一个dist文件里面有一个main.js
这个时候webpack默认会找根文件下的src/index.js 打包
二、新建打包配置文件webpack.config.js
因为需要在node中运行,需要用commonjs来写配置文件
/*** 类型提示* @type {import("webpack").Configuration}*/
const config = {};
module.exports = config;
配置入口和输出文件
/*** 类型提示* @type {import("webpack").Configuration}*/
const config = {entry: './src/index.js',output: {filename: 'build.js',path: './build'}
};
module.exports = config;
这个时候打包会报错,这是因为输出文件必须是一个绝对路径,
需要用到node的path这个包,通过path.resolve(__dirname, './build')获取绝对路径
const path = require('path')/*** 类型提示* @type {import("webpack").Configuration}*/
const config = {entry: './src/index.js',output: {filename: 'build.js',path: path.resolve(__dirname, './build')}
};
module.exports = config;
看看打包的文件
这个时候我们写ESModule CommonJS AMD CMD,webpack都能把我们的文件转成浏览器兼容的js文件
三、如何修改打包文件名
我们将webpack.config.js改为word.config.js,如何让webpack识别打包的配置文件
需要修改package.json的打包命令 --config 指定打包文件
{"name": "webpack-cs","version": "1.0.0","description": "","main": "index.js","scripts": {"build": "webpack --config ./word.config.js"},"keywords": [],"author": "","license": "ISC","devDependencies": {"webpack": "^5.89.0","webpack-cli": "^5.1.4"}
}
下一章我们开始处理css