TS(TypeScript)— 搭建開發環境

萬事順意發表於2024-04-03

1.建立pakeage.json

npm init  //自選引數
npm init -y //預設引數

2.構造目錄

  • 安裝ts開發依賴
npm install typescript tslint -g
  • 建立功能資料夾

  • 初始化ts(安裝typescript就可以使用tsc命令)生成tsconfig.json檔案
 tsc --init

  • 配置webpack
npm install webpack webpack-cli webpack-dev-server -D
 npm install clean-webpack-plugin html-webpack-plugin -D
 npm cross-env -D    
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path = require('path');

module.exports = {
  entry: "./src/index.ts",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, 'dist') // 新增輸出目錄路徑
  },
  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: {
    static: { // 替換 contentBase
      directory: path.join(__dirname, 'dist'), // 指定提供靜態檔案的目錄
    },
    client: {
      logging: 'error' // 僅顯示錯誤資訊
    },
    compress: false,
    host: 'localhost',
    port: 8089
  },
  plugins: [
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: [
        './dist'
      ]
    }),
    new HtmlWebpackPlugin({
      template: './src/template/index.html'
    })
  ]
};
  • 配置打包環境
npm install cross-env -D
{
  "name": "tslearning",
  "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"
  },
  "keywords": [
    "typescript"
  ],

相關文章