最近在学习webpack打包,顺便做了一下笔记用来总结.后续继续补充
对项目进行初始化生成package.json文件
npm init -y
通过npm或cnpm下载webpack打包工具以及ts->js转换器
cnpm i -D webpack webpack-cli typescript ts-loader
创建webpack.config.js文件并且进行ts的相关配置
//引入一个包
const path = require('path');
module.exports = {
//入口文件
entry: "./src/index.ts",
//打包输出路径
output:{
path: path.resolve(__dirname,'dist'),
filename: "bundle.js",
},
//打包的模块
module:{
//指定加载规则
rules:[
{
//匹配规则
test: /\.ts$/,
//use从后往前加载
use: [
'ts-loader'
],
//不参与编译的模块
exclude: /node_modules/
}
]
}
}
通过npm下载能将ts转化为html文件的插件 html-webpack-plugin ,并且在webpack.config.js中配置
cnpm i -D html-webpack-plugin
const HTMLWebpackPlugin = require('html-webpack-plugin');
module.exports = {
//入口文件
entry: "./src/index.ts",
//打包输出路径
output:{
},
//打包的模块
module:{
//指定加载规则
rules:[]
},
//配置插件
plugins:[
// new HTMLWebpackPlugin({
// title: '自定义函数'
// })
// new CleanWebpackPlugin(),
new HTMLWebpackPlugin({
template: './src/index.html'
})
],
}
通过npm 下载能对js代码进行兼容性打包的babel模块 ,并且在webpack.config.js中配置
cnpm i -D @babel/core @babel/preset-env babel-loader core-js
//打包的模块
module:{
//指定加载规则
rules:[
{
test: /\.ts$/,
//use从后往前加载
use: [
//配置babel
// 'babel-loader',
{
//指定加载器
loader: 'babel-loader',
//设置babel
options:{
//设置定义的环境
presets:[
[
//指定环境的插件
"@babel/preset-env",
//配置信息
{
//要兼容的目标浏览器
targets:{
"chrome":"88",
"ie": "11"
},
//指定的core.js版本
"corejs": "3",
//使用core.js的方式--按需加载
"useBuiltIns": "usage"
}
]
]
}
},
'ts-loader'
],
exclude: /node_modules/
}
]
},
在packjson中配置打包命令 npm run build--自动在dist文件夹生成bundel.js文件和html文件 npm start--打开的html文件实时更新ts中的打包内容,类似于vue项目的npm run serve。
{
"name": "03webpacktest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode production",
"start": "webpack serve --open --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.18.5",
"@babel/preset-env": "^7.18.2",
"babel-loader": "^8.2.5",
"core-js": "^3.23.3",
"html-webpack-plugin": "^5.5.0",
"ts-loader": "^9.3.1",
"typescript": "^4.7.4",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0"
}
}
补充:ts配置文件生成以及less加载器的配置
ts配置文件生成命令
tsc -init
{
"include":{},
"compilerOptions": {
"target": "es2016",
"module": "es2016",
"strict": true,
}
}
下载less包的命令
npm i -D less less-loader css-loader style-loader
下载使css兼容不同老旧浏览器的包postcss
npm i -D postcss postcss-loader postcss-preset-env
配置less加载器以及兼容加载器postcss
//设置less文件的处理
{
test: /\.less$/,
use:[
"style-loader",
"css-loader",
//引入postcss
{
loader: "postcss-loader",
options:{
postcssOptions:{
plugins:[
[
"postcss-preset-env",
{
browsers: 'last 2 version'
}
]
]
}
}
},
"less-loader"
]
}