Webpack打包TS
# 使用Webpack打包TS
# 整体项目结构
# 🍤1.初始化工程
主要创建public存放html
文件等,创建src存放js
文件等,创建build存放webpack.config.js
的文件。
$ npm init -y
$ tsc --init
$ mkdir build public src
$ ls
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2022/8/30 17:35 build
d----- 2022/8/30 17:40 node_modules
d----- 2022/8/30 16:28 public
d----- 2022/8/30 17:23 src
-a---- 2022/8/30 17:40 547793 package-lock.json
-a---- 2022/8/30 17:40 674 package.json
-a---- 2022/8/30 16:30 11401 tsconfig.json
# 🍤2.下载依赖
$ npm install -D typescript
$ npm install -D webpack@4.41.5 webpack-cli@3.3.10 webpack-dev-server@3.10.2
$ npm install -D html-webpack-plugin@4.5.0 clean-webpack-plugin@3.0.0 ts-loader@8.0.11 cross-env@7.0.2
// 此处为package.json的内容
"devDependencies": {
"clean-webpack-plugin": "^3.0.0",
"cross-env": "^7.0.2",
"html-webpack-plugin": "^4.5.0",
"ts-loader": "^8.0.11",
"typescript": "^4.0.5",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.2"
},
# 🍤3.入口
入口JS: src/main.ts
document.write('Hello Webpack TS!')
# 🍤3.index页面
index页面: public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>webpack & TS</title>
</head>
<body>
</body>
</html>
# 🍤4.打包配置
webpack的配置:build/webpack.config.js
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const isProd = process.env.NODE_ENV === 'production' // 是否生产环境
function resolve (dir) {
return path.resolve(__dirname, '..', dir)
}
module.exports = {
mode: isProd ? 'production' : 'development',
entry: {
app: './src/main.ts'
},
output: {
path: resolve('dist'),
filename: '[name].[contenthash:8].js'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
include: [resolve('src')]
}
]
},
plugins: [
new CleanWebpackPlugin({
}),
new HtmlWebpackPlugin({
template: './public/index.html'
})
],
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
devtool: isProd ? 'cheap-module-source-map' : 'cheap-module-eval-source-map',
devServer: {
host: 'localhost', // 主机名
stats: 'errors-only', // 打包日志输出输出错误信息
port: 8081,
open: true
},
}
# 🍤5.配置打包命令
{
"name": "webpack_vue",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
// 添加为这两行内容
"dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.config.js",
"build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^3.0.0",
"cross-env": "^7.0.2",
"html-webpack-plugin": "^4.5.0",
"ts-loader": "^8.0.11",
"typescript": "^4.0.5",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.2"
},
"dependencies": {
"vue": "^3.2.38"
}
}
# 🍤6.运行和打包
$ npm run dev
$ npm run build
上次更新: 2023/11/28, 22:03:59