Typescript 结合 Webpack 搭建开发环境

项目环境搭建

目录结构搭建

  1. npm init -y 初始化package.json
  • 配置"main": "./src/index.ts"
  1. 创建目录src
  • api
  • assets
  • config
  • template > index.html
  • tools
  • utils
  • index.ts
  1. 根目录下文件
  • package.json
  • src
  • typings
  • build > webpack.config.js

安装依赖

  • npm install typescript tslint -g

  • tsc --init

  • npm install webpack webpack-cli webpack-dev-server -D

  • npm install cross-env -D

  • npm install clean-webpack-plugin html-webpack-plugin -D

  • npm install typescript

  • npm install ts-loader --save-dev

启动和打包

  • npm start

  • npm run build

目录结构

在这里插入图片描述

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
    entry: './src/index.ts',
    output: {
        filename: 'main.js'
    },
    resolve: {
        extensions: ['.ts', '.tsx','.js']
    },
    module: {
        rules: [ {
            test: /\.tsx?$/,
            use: 'ts-loader',
            exclude: /node_modules/
        }]
    },
    devtool: process.env.NODE_ENV === 'production' ? false : 'inline-source-map',
    devServer: {
        contentBase: './dist',
        stats: 'errors-only',
        compress: false,
        host: 'localhost',
        port: 8080
    },
    plugins: [
        new CleanWebpackPlugin({
            cleanOnceBeforeBuildPatterns: ['./dist']
        }),
        new HtmlWebpackPlugin({
            template: './src/template/index.html'
        })
    ]
}

package.json

{
  "name": "ts_demo",
  "version": "1.0.0",
  "description": "",
  "main": "./src/index.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "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"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "cross-env": "^7.0.2",
    "html-webpack-plugin": "^4.2.0",
    "ts-loader": "^7.0.1",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  },
  "dependencies": {
    "typescript": "^3.8.3"
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值