与webpack整合
# 创建项目文件夹
mkdir tswp && cd tswp
# 初始化npm,生成package.json
$ npm init -y
# -D 代表开发包 ts-loader 是webpack的加载器,用于整合webpack
$ npm i -D webpack webpack-cli typescript ts-loader
# 创建src目录以及ts源码文件
mkdir src && cd src
echo 'console.log("hello world");' > index.ts
创建webpack配置文件webpack.config.js
:
// 引入path包
const path = require("path")
// webpack中的所有配置信息都应该卸载 module.exports中
module.exports = {
// 入口文件
entry: "./src/index.ts",
// 指定打包文件目录
output: {
// 指定打包目录
path: path.resolve(__dirname, 'dist'),
// 指定打包后的文件
filename: 'bundle.js'
},
// 指定webpack打包时要使用的模块
module: {
// 指定加载规则
rules: [
{
// 指定规则生效的文件,这里是ts文件
test: /\.ts$/,
// 处理方式
use: 'ts-loader',
// 指定要排除的文件
exclude: /node_modules/
}
]
}
}
创建tsc的配置文件tsconfig.json
:
{
"compilerOptions": {
"target": "ES2015",
"module": "ES2015",
"strict": true
}
}
给npm增加build命令,让其使用webpack编译构建, 注意build,如下是package.json
:
{
"name": "tswp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^9.2.5",
"typescript": "^4.4.3",
"webpack": "^5.53.0",
"webpack-cli": "^4.8.0"
}
}
最后更新于
这有帮助吗?