手把手 ts+webpack 搭建環境

👇👇
項目地址

初始化項目

創建文件 ts-demo

npm init -y

npm i typescript -D

初始化 ts配置項

npx tsc --init

目錄結構

ts-demo
│   README.md 
│
└───build
│   │   webpack.base.config.js
│   │   webpack.config.js
│   │   webpack.pro.config.js
|   |   webpack.dev.config.js
│   
└───public
|   |  index.html
|   |
└───src
|    │   template
|    │   test
|
└─── .eslintrc.js
└─── tsconfig.json
|
└─── REAME.md

webpack 配置

build目錄構建 webpack 配置

npm install --save-dev webpack webpack-cli webpack-dev-server ts-loader html-webpack-plugin webpack-merge clean-webpack-plugin

入口配置webpack.config.js

const merge = require('webpack-merge');
const basicConfig=require('./webpack.base.config');
const devConfig=require('./webpack.dev.config');
const prodConfig=require('./webpack.pro.config')

const config=process.NODE_ENV==='development'?devConfig:prodConfig;

module.exports=merge(basicConfig,config)

基礎配置webpack.base.config.js

const path=require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports={
    entry:{
      app:'./src/index.ts'
    },
  
    resolve: {
        extensions: [ '.tsx', '.ts', '.js' ]
    },
    module: {
        rules: [  
          {
            test: /\.tsx?$/,
            use: 'ts-loader',
            exclude: /node_modules/
          }
        ]
      },
    plugins:[
        new HtmlWebpackPlugin({
            title:'webpack-ts-deno',
            template:'./src/template/index.html'
        })
    ],
    output:{
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, '../dist')
    }
}

開發環境配置webpack.dev.config.js

const { CleanWebpackPlugin } =require('clean-webpack-plugin');

module.exports={
    plugins:[
        new  CleanWebpackPlugin(),
    ]
}

生產環境配置webpack.pro.config.js

module.exports={
    devtool: 'cheap-module-eval-source-map',
}

修改package.json腳本

"scripts": {
    "dev": "webpack-dev-server --mode=development --config  ./build/webpack.config.js",
    "build": "webpack --mode=production --config ./build/webpack.config.js"
  }

代碼檢查規範 eslint 配置

npm i -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser

@typescript-eslint/parser 爲eslint 解析 ts

初始化 eslint 配置

npx eslint --init

module.exports = {
    "parser": "@typescript-eslint/parser",  
    "parserOptions": {
        "project":"./tsconfig.json",
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 2018,
        "sourceType": "module"
    },
    "extends":[
      "plugin:@typescript-eslint/recommended"
    ],
    "plugins": [
        "react",
        "@typescript-eslint"
    ],
    "rules": {
    }
};

添加腳本 package.json

"scripts": {
 "lint":"eslint src --ext .js,.ts",
}

測試環境搭建

npm i jest ts-jest

生成jest 配置文件

npx ts-jest config:init

添加腳本package.json

"scripts": {
 "test":"jest",
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章