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"
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章