功能分析
初始化项目
TypeScript libray starter
git clone https://github.com/alexjoverm/typescript-library-starter.git ts-axios
npm i
关联远程仓库
git remote add origin https://gitee.com/username/ts-axios.git
git pull origin master
git add .
npm run commit
创建入口文件
// ./src/index.ts
import {AxiosRequestConfig} from './type'
import xhr from './xhr'
function axios(config: AxiosRequestConfig): void {
// TODO
xhr(config)
}
export default axios
// ./src/type/index.ts
export type Method = 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
export interface AxiosRequestConfig {
url: string
method?: Method
data?: any
params?: any
}
// ./xhr.ts
import { AxiosRequestConfig } from './type'
export default function xhr(config: AxiosRequestConfig) {
const { data = null, url, method = 'get' } = config
const request = new XMLHttpRequest()
request.open(method.toUpperCase(), url, true)
request.send(data)
}
Demo
依赖安装
npm i --save-dev webpack webpack-dev-middleware webpack-hot-middleware ts-loader tslint-loader express body-parser
webpack配置
./examples/webpack.config.js
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
module.exports = {
mode: 'development',
entry: fs.readdirSync(__dirname).reduce((entries, dir) => {
const fullDir = path.join(__dirname, dir)
const entry = path.join(fullDir, 'app.ts')
if (fs.statSync(fullDir).isDirectory() && fs.existsSync(entry)) {
entries[dir] = ['webpack-hot-middleware/client', entry]
}
return entries
}, {}),
output: {
path: path.join(__dirname, '__build__'),
filename: '[name].js',
publicPath: '/__build__/'
},
module: {
rules: [
{
test: /\.ts$/,
enforce: 'pre',
use: [
{
loader: 'tslint-loader'
}
]
},
{
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true
}
}
]
}
]
},
resolve: {
extensions: ['.ts', '.tsx','.js']
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
]
}
./examples/server.js
const express = require('express')
const bodyParser = require('body-parser')
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddelware = require('webpack-hot-middleware')
const WebpackConfig = require('./webpack.config')
const app = new express()
const compiler = webpack(WebpackConfig)
app.use(webpackDevMiddleware(compiler, {
publicPath: '/__build__/',
stats: {
colors: true,
chunks: false
}
}))
app.use(webpackHotMiddelware(compiler))
app.use(express.static(__dirname))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
const router = express.Router()
router.get('/simple/get', (req, res) => {
res.json({
msg: 'hello world'
})
})
app.use(router)
const port = process.env.PORT || 8080
module.exports = app.listen(port, () => {
console.log(`Serve listening on http://localhost:${port}, Ctrl + C to stop`)
})
./examples/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ts-axios examples</title>
</head>
<body>
<h1>ts-axios example</h1>
<ul>
<li><a href="simple">Simple</a></li>
</ul>
</body>
</html>
./examples/global.css
./examples/simple/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple example</title>
</head>
<body>
<script src="/__build__/simple.js"></script>
</body>
</html>
./examples/simple/app.ts
import axios from '../../src/index'
axios({
method: 'get',
url: '/simple/get',
params: {
a: 1,
b: 2
}
})
./packages.json
{
"name": "ts-axios",
"version": "0.0.0",
"description": "",
"keywords": [],
"main": "dist/ts-axios.umd.js",
"module": "dist/ts-axios.es5.js",
"typings": "dist/types/ts-axios.d.ts",
"files": [
"dist"
],
"author": "cell <1746806993@qq.com>",
"repository": {
"type": "git",
"url": ""
},
"license": "MIT",
"engines": {
"node": ">=6.0.0"
},
"scripts": {
"dev": "node examples/server.js",
"lint": "tslint --project tsconfig.json -t codeFrame 'src/**/*.ts' 'test/**/*.ts'",
"prebuild": "rimraf dist",
"build": "tsc --module commonjs && rollup -c rollup.config.ts && typedoc --out docs --target es6 --theme minimal --mode file src",
"start": "rollup -c rollup.config.ts -w",
"test": "jest --coverage",
"test:watch": "jest --coverage --watch",
"test:prod": "npm run lint && npm run test -- --no-cache",
"deploy-docs": "ts-node tools/gh-pages-publish",
"report-coverage": "cat ./coverage/lcov.info | coveralls",
"commit": "git-cz",
"semantic-release": "semantic-release",
"semantic-release-prepare": "ts-node tools/semantic-release-prepare",
"precommit": "lint-staged",
"travis-deploy-once": "travis-deploy-once"
},
"lint-staged": {
"{src,test}/**/*.ts": [
"prettier --write",
"git add"
]
},
"config": {
"commitizen": {
"path": "node_modules/cz-conventional-changelog"
}
},
"jest": {
"transform": {
".(ts|tsx)": "ts-jest"
},
"testEnvironment": "node",
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"/test/"
],
"coverageThreshold": {
"global": {
"branches": 90,
"functions": 95,
"lines": 95,
"statements": 95
}
},
"collectCoverageFrom": [
"src/*.{js,ts}"
]
},
"prettier": {
"semi": false,
"singleQuote": true
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"devDependencies": {
"@commitlint/cli": "^7.1.2",
"@commitlint/config-conventional": "^7.1.2",
"@types/jest": "^23.3.2",
"@types/node": "^10.11.0",
"body-parser": "^1.19.0",
"colors": "^1.3.2",
"commitizen": "^3.0.0",
"coveralls": "^3.0.2",
"cross-env": "^5.2.0",
"cz-conventional-changelog": "^2.1.0",
"express": "^4.17.1",
"husky": "^1.0.1",
"jest": "^23.6.0",
"jest-config": "^23.6.0",
"lint-staged": "^8.0.0",
"lodash.camelcase": "^4.3.0",
"prettier": "^1.14.3",
"prompt": "^1.0.0",
"replace-in-file": "^3.4.2",
"rimraf": "^2.6.2",
"rollup": "^0.67.0",
"rollup-plugin-commonjs": "^9.1.8",
"rollup-plugin-json": "^3.1.0",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-sourcemaps": "^0.4.2",
"rollup-plugin-typescript2": "^0.18.0",
"semantic-release": "^15.9.16",
"shelljs": "^0.8.3",
"travis-deploy-once": "^5.0.9",
"ts-jest": "^23.10.2",
"ts-loader": "^6.2.1",
"ts-node": "^7.0.1",
"tslint": "^5.11.0",
"tslint-config-prettier": "^1.15.0",
"tslint-config-standard": "^8.0.1",
"tslint-loader": "^3.5.4",
"typedoc": "^0.12.0",
"typescript": "^3.0.3",
"webpack": "^4.41.6",
"webpack-dev-middleware": "^3.7.2",
"webpack-hot-middleware": "^2.25.0"
}
}
测试运行
npm run dev