webpack 中配置 typescript
时间: 2023-11-30 15:08:39 浏览: 37
在使用Webpack配置TypeScript时,你需要进行以下步骤:
1. 安装依赖:
```
npm install webpack webpack-cli typescript ts-loader --save-dev
```
2. 在项目根目录下创建 `tsconfig.json` 文件,并配置TypeScript编译选项:
```json
{
"compilerOptions": {
"target": "es5",
"module": "es6",
"moduleResolution": "node", "sourceMap": true,
"esModuleInterop": true,
"strict": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
```
3. 在Webpack配置文件中进行以下配置:
```javascript
const path = require('path');
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
}
};
```
这里假设你的入口文件是 `src/index.ts`,输出文件为 `dist/bundle.js`。`resolve.extensions`选项用于指定解析模块时的文件后缀名。
4. 创建你的TypeScript源文件,例如 `src/index.ts`。
5. 运行Webpack编译你的代码:
```
npx webpack
```
或者使用npm脚本,在`package.json`中添加如下配置:
```
"scripts": {
"build": "webpack"
}
```
然后可以使用以下命令运行编译:
```
npm run build
```
以上就是在Webpack中配置TypeScript的基本步骤。你可以根据需要进行进一步的配置,例如添加Babel支持、优化打包等。