ts09_使用webpack打包ts文件2
1.为了对html文件进行自动生成和一些资源的自动按需引入还需要对webpack继续进行一些配置,首先需要安装html-webpack-plugin插件帮助我们自动生成html文件
运行npm i -D html-webpack-plugin
2.引入html-webpack-plugin
const HTMLWEBPACKPLUGIN = require('html-webpack-plugin')
3.在webpack.config.js文件中配置plugins选项来引入要使用的插件

4.为了能让代码修改后自动打包页面自动刷新还需要进行一些配置,下载webpack-dev-server
运行npm i -D webpcak-dev-server
安装好之后在packge.json文件中配置脚本

然后运行nmp run start 如果出现以下 错误

这个错误的意思是项目需要一个运行环境的模式,为“development” 或者“production”;
需要在webpack.config.js中配置mode选项来确定运行环境

5.为了确保每次打包的dist文件都是最新的,需要在打包之前清除dist目录,还需要安装一个插件 clean-webpack-plugin
运行命令 npm i -D clean-webpack-plugin 安装插件
引入插件
const {CleanWebpackPlugin} = require("clean-webpack-plugin")
在plugins里面配置
6.最后还需要配置一下resolve选项告诉webpack哪些文件可以被当做模块使用

到这里webpack打包JS文件的一些最基本的配置就完成了
webpack.config.js
//引入path模块,管理路径
// import { Configuration } from 'webpack';//运行webpack时注释掉
/**
* @type {Configuration}
*/
const path = require('path');
//引入html-webpack-plugin
const HTMLWEBPACKPLUGIN = require('html-webpack-plugin')
const {CleanWebpackPlugin} = require("clean-webpack-plugin")
//webpack中的所有配置信息都应写在module.exports中
module.exports = {
//指定入口文件
entry: './src/index.ts',
//指定打包文件所在目录
output: {
//指定打包文件的目录
// path:'./dist'
path: path.resolve(__dirname, 'dist'),
//打包后文件的文件名
filename: "bundle.js"
},
//指定webpack打包时要使用的模块
module: {
//指定加载的规则
rules: [
{
//指定规则生效的文件
test: /\.ts$/,
//要是用的loader
use: "ts-loader",
//指定要排除的文件
exclude: /node_modules/,
}
]
},
//配置webpack的插件
plugins: [
new CleanWebpackPlugin(),
new HTMLWEBPACKPLUGIN({
// title:'这是一个自定义的title'//用来配置自动生成的html文件的title
template:"./src/index.html"//用来配置自动生成的html文件的模板
})
],
mode:'development',
resolve:{
//设置引用模块
extensions:['.ts','js']//告诉webpack哪些后缀的文件可以被当做模块引用
}
}
package.json文件
{
"name": "part3",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode production",
"dev": "webpack --mode development",
"start": "webpack serve --open "
},
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"ts-loader": "^9.4.2",
"typescript": "^4.9.4",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"webpack-dev-server": "^4.11.1"
}
}

浙公网安备 33010602011771号