Uni-app + Vue3 + TS basic project construction
Basic introduction to
My personal background is because the company’s business covers many small programs, including Alipay small program, wechat small program, Baidu small program and Kuaiya. The project is based on NPM package management, vscode related plug-ins to provide better development experience.
- Uni-app/vue3 / typescript/axios/sass/esLint/prettier
Let’s go ahead and build a usable initial project from scratch. If “needs are urgent” refer to the GitHub source code at the bottom. If you encounter problems, refer to the corresponding steps.
Install uni-app using NPM
NPM install -g@vue /cli vue create -p dcloudio/uni- vue#vue3 uni-app-vue3-demo // Wait a moment... > Please select uni-app template: The default template (TypeScript) CD uni - app - vue3 - demo NPM install / / installing a slower can use NPM install - / / registry=https://registry.npm.taobao.org NPM uninstall vue-class-component vue-property-decorator // Update package NPM install [email protected] [email protected] [email protected]Copy the code
Example Configure esLint + prettier to automatically format code
Install related NPM packages
npm install eslint prettier --save-dev
npm install eslint-config-prettier eslint-plugin-prettier eslint-plugin-vue --save-dev
npm install @typescript-eslint/eslint-plugin @typescript-eslint/parser --save-dev
Copy the code
Install related plug-ins
- Prettier – Code formatter
- ESLint
Eslint configuration.eslintrc.js
module.exports = {
parser: 'vue-eslint-parser'.extends: ['plugin:vue/recommended'.'plugin:prettier/recommended'].parserOptions: {
parser: '@typescript-eslint/parser'.ecmaVersion: 2018.sourceType: 'module',},plugins: ['vue'.'@typescript-eslint'],}Copy the code
Prettier configuration.prettierrc.js
module.exports = {
printWidth: 120.tabWidth: 2.tabs: false.semi: false.singleQuote: true.quoteProps: 'as-needed'.bracketSpacing: true.jsxBracketSameLine: false.arrowParens: 'always'.endOfLine: 'auto',}Copy the code
Vscode configuration.vscode/settings.json
{
"vetur.validation.template": false."editor.formatOnSave": true."editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"elint.validate": ["typescript"."vue"."html"."json"]."editor.defaultFormatter": "esbenp.prettier-vscode"."[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[vue]": {
"editor.defaultFormatter": "rvest.vs-code-prettier-eslint"
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"json.format.enable": false
}
Copy the code
Test code for automatic formatting
Restart vscode, open SRC pages/index.vue, enter a few Spaces and save to see if it is automatically formatted
The Typescript configuration allows the default any typetsconfig.json
{
compilerOptions: {
"noImplicitAny": false,
}
}
Copy the code
Configuration SASS
Install NPM related packages
NPM install [email protected] [email protected] --save-dev // If you encounter installation problems, add // delete package.json devDependencies Node_modules then reinstall NPM installCopy the code
Used in VUE
<style lang="scss">
</style>
Copy the code
Configure global public variables and import them automatically
Create a global style variablestyle/var.scss
$test-size: 400rpx;
Copy the code
Auto import globallyvue.config.js
process.env.UNI_USING_VUE3 = true
process.env.UNI_USING_VUE3_OPTIONS_API = true
module.exports = {
css: {
loaderOptions: {
sass: {
prependData: `@import "@/styles/var.scss"; `.// Introduce global variables}},},configureWebpack: {
resolve: {
extensions: ['.js'.'.ts'.'.vue'.'.json'],}}},Copy the code
Vscode related plug-ins
- SCSS IntelliSense installation prompts global style variables (as shown below)
Install axiOS API layer adaptation applets
import axios, { AxiosError } from 'axios'
import qs from 'qs'
let TOKEN_KEY = 'x-token' // TODO is configured according to its own backend
let API_SOURCE = ' '
// #ifdef MP-WEIXIN
API_SOURCE = 'weixin' // Wechat applets
// #endif
// #ifdef MP-BAIDU
API_SOURCE = 'bdapplets' // Baidu small program
// #endif
// Set the form type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
let baseURL = process.env.VUE_APP_API_HOST
const fetch = axios.create({
withCredentials: true,
baseURL,
timeout: 5000,})let jumpLoginCount = 0
// The request interceptor does some processing before the request is made
fetch.interceptors.request.use(
(config) = > {
Object.assign(config.headers, {
Authorization: uni.getStorageSync(TOKEN_KEY),
})
config.data = qs.stringify(config.data)
return config
},
(error) = > {
return Promise.reject(error)
}
)
// Successfully configured interceptor
fetch.interceptors.response.use(
(res) = > {
const params = qs.parse(res.config.data)
/ / set the token
if (res.headers.Authorization) {
uni.setStorageSync(TOKEN_KEY, res.headers.Authorization)
}
// TODO is configured based on the backend success status
if (['20001'].includes(`${res.data.code}`)) {
// Whether to return the root data
if (params.rootResult) return res
else return res.data
} else {
return Promise.reject(res.data)
}
},
(error: AxiosError) = > {
const params = qs.parse(error.config.data)
// The login page is displayed
if(error.response! .status ==401) {
if (jumpLoginCount == 0) {
uni.navigateTo({
url: '/pages/login/index'.// TODO is configured as its own login page path
})
++jumpLoginCount
setTimeout(() = > (jumpLoginCount = 0), 2000)}return Promise.reject(error)
}
return Promise.reject(error)
}
)
// adapt applets
fetch.defaults.adapter = function (config: any) {
return new Promise((resolve, reject) = > {
var settle = require('axios/lib/core/settle')
var buildURL = require('axios/lib/helpers/buildURL')
uni.request({
method: config.method.toUpperCase(),
url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
header: config.headers,
data: config.data,
dataType: config.dataType,
responseType: config.responseType,
sslVerify: config.sslVerify,
complete: function complete(response: any) {
response = {
data: response.data,
status: response.statusCode,
errMsg: response.errMsg,
headers: response.header, // Note the plural number here
config: config,
}
settle(resolve, reject, response)
},
})
})
}
export { fetch, API_SOURCE }
Copy the code
conclusion
After the above steps, you can have a pleasant trip to the pit ~ if necessary access to the source code uni-app-vue3-demo