webpack配置打包ts

这篇博客详细介绍了如何配置webpack来打包TypeScript项目。首先,通过npm安装相关依赖,如typescript、webpack及其插件。接着,创建src/main.ts作为入口文件,public/index.html作为HTML模板,并生成tsconfig.json配置文件。在build文件夹下创建webpack.config.js进行配置。最后,设置命令行脚本,根据需求运行打包命令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装依赖

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 clean-webpack-plugin cross-env ts-loader

新建入口js: src/main.ts

document.write('哈哈哈')

新建public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>webpack</title>
</head>
<body>
    
</body>
</html>

生成 tsconfig.json

先全局安装typescript npm install -g typescript
tsc --init
如果出现 因为在此系统上禁止运行脚本 的情况 可以以管理员身份运行Windows PowerShell 使用 get-executionpolicy 查看脚本执行策略
再执行指令 set-executionpolicy RemoteSigned 就可以tsc --init了

新建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, // 是否自动在默认浏览器内打开localhost:8081
  },
}

配置命令行

// package.json
"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"
  },

最后根据需求运行命令就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值