TS搭建运行环境—webpack
- 初始化package.josn,记录项目中的相关依赖
npm init
- 安装webpack和webpack-cli
npm install webpack webpack-cli -D
- 配置webpack.config.js
const path = require("path")
const HtmlWeabpckPlugin = require("html-webpack-plugin")
module.exports = {
mode: "development",
entry: "./src/index.ts",
output: {
path: path.resolve(__dirname, "./dist"),
filename: "bundle.js"
},
resolve: {
extensions: [".ts", ".js", ".cjs", ".json"]
},
devServer: {},
module: {
rules: [
{
test: /\.ts$/,
loader: "ts-loader"
},
{
test: /\.(png|jpe?g|svg|gif)$/,
type: "asset/resource"
}
]
},
plugins: [
new HtmlWeabpckPlugin({
template: "./index.html"
})
]
}
- 安装ts-loader
npm install ts-loader -D
- ts-loader依赖于tsconfig.json
tsc --init
- 安装html-webpack-plugin
npm install html-webpack-plugin -D
- 开启一个本地服务依赖于webpack-dev-server
npm install webpack-dev-server -D
- package.json/scripts
"serve": "webpack serve",
"build": "webpack"
- 开启一个本地服务
npm run serve
注意:若是tsconfig.json无故报错,是由于该文件的同级目录下,没有ts文件,所以会报这种类似于语法错误的,只要在同级下创建一个ts文件即可。