环境搭建:
初始化项目:
npm init -y
安装你所需的依赖:
如:
npm i -D webpack webpack-cli typescript ts-loader
cnpm i -D @babel/core @babel/core @babel/preset-env babel-loader core-js
cnpm i -D html-webpack-plugin
cnpm i -D webpack-dev-server
cnpm i -D clean-webpack-plugin
然后配置如下文件:
tsconfig.json
{
"compilerOptions": {
"module": "es6",
"target": "es6",
"strict": true
}
}
webpack.config.js
//npm init -y
// npm i -D webpack webpack-cli typescript ts-loader
//cnpm i -D @babel/core @babel/core @babel/preset-env babel-loader core-js
//引入一个包
const path =require('path');
//引入html插件 cnpm i -D html-webpack-plugin
const HTMLWebpackPlugin = require('html-webpack-plugin');
//cnpm i -D webpack-dev-server
//webpack中的所有配置信息都应该写在 module.exports中
//引入clean插件 cnpm i -D clean-webpack-plugin
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
module.exports ={
//指定入口文件
entry:"./src/index.ts",
//指令打包文件所在的目录
output:{
//指定打包后的目录
path:path.resolve(__dirname,'dist'),
//打包后文件名字
filename:"bundle.js",
//告诉webpack不使用箭头函数
environment:{
arrowFunction:false
}
},
//指定webpack打包时要使用的模块
module:{
//指定加载规则
rules:[
{
//test指定规则生效的文件
test: /\.ts$/,
// 要使用的loader
use: [
// 配置babel
{
// 指定加载器
loader:"babel-loader",
// 设置babel
options: {
// 设置预定义的环境
presets:[
[
// 指定环境的插件
"@babel/preset-env",
// 配置信息
{
// 要兼容的目标浏览器
targets:{
"chrome":"58",
"ie":"11"
},
// 指定corejs的版本
"corejs":"3",
// 使用corejs的方式 "usage" 表示按需加载
"useBuiltIns":"usage"
}
]
]
}
},
'ts-loader'
],
//要排除的文件
exclude: /node_modules/
}
]
},
//配置webpack插件
plugins:[
new CleanWebpackPlugin(),
new HTMLWebpackPlugin({
// title: '自定义标题'
template:"./index.html"
})
],
//用来设置引用模块
resolve:{
extensions:['.ts','.js']
}
}
package.json:
{
"name": "part3",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack serve --open chrome.exe"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.13.10",
"@babel/preset-env": "^7.13.12",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^3.0.0",
"core-js": "^3.9.1",
"html-webpack-plugin": "^5.3.1",
"ts-loader": "^8.0.18",
"typescript": "^4.2.3",
"webpack": "^5.28.0",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
}
}
配置成功运行:npm start
文件目录如下:
学习路径