初探webpack之从零搭建Vue开发环境 (5)

我们还可以配置一下lint-staged,在ESLint检查有错误自动修复,无法修复则无法执行git add。

$ yarn add -D lint-staged husky $ npx husky install $ npx husky add .husky/pre-commit "npx lint-staged" // package.json { // ... "lint-staged": { "*.{js,vue,ts}": [ "eslint --fix" ] } } 配置TypeScript

虽然是Vue2对ts支持相对比较差,但是至少对于抽离出来的逻辑是可以写成ts的,可以在编译期就避免很多错误,对于一些Vue2 +TS的装饰器写法可以参考之前的博客 ,本次的改动比较大,主要是配置了ESLint相关信息,处理TS与Vue文件的提示信息,webpack.config.js配置resolve的一些信息以及ts-loader的解析,对于.vue的TS装饰器方式修改,src/sfc.d.ts作为.vue文件的声明文件,VueRouter与Vuex的TS修改,以及最后的tsconfig.json用以配置TS信息,配置TypeScript完成之后的commit id为0fa9324。

yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser @babel/plugin-syntax-typescript typescript vue-property-decorator vue-class-component ts-loader vuex-class // .eslintrc.js module.exports = { parser: "vue-eslint-parser", extends: ["eslint:recommended", "plugin:prettier/recommended"], overrides: [ { files: ["*.ts"], parser: "@typescript-eslint/parser", plugins: ["@typescript-eslint"], extends: ["plugin:@typescript-eslint/recommended"], }, { files: ["*.vue"], parser: "vue-eslint-parser", extends: [ "plugin:vue/recommended", "plugin:prettier/recommended", "plugin:@typescript-eslint/recommended", ], }, ], parserOptions: { ecmaVersion: 2020, sourceType: "module", parser: "@typescript-eslint/parser", }, // ... }; // src/sfc.d.ts declare module "*.vue" { import Vue from "vue/types/vue"; export default Vue; } <!-- src/views/framework.vue --> <!-- ... --> <script lang="ts"> import { Component, Vue } from "vue-property-decorator"; import { State } from "vuex-class"; @Component export default class FrameWork extends Vue { protected msg = "Example"; @State("text") text!: string; protected toast() { window?.alert("ExampleMessage"); } protected setVuexValue() { this.$store.commit("setText", "New Value"); } } </script> <!-- ... --> // tsconfig.json { "compilerOptions": { "target": "esnext", "module": "esnext", "strict": true, "jsx": "preserve", "importHelpers": true, "moduleResolution": "node", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "experimentalDecorators":true, "sourceMap": true, "skipLibCheck": true, "baseUrl": ".", "types": [], "paths": { "@/*": [ "./src/*" ] }, "lib": [ "esnext", "dom", "es5", "ES2015.Promise", ] }, "exclude": [ "node_modules" ] } // webpack.config.js // ... module.exports = { mode: process.env.NODE_ENV, entry: "./src/index", output: { filename: "index.js", path: path.resolve(__dirname, "dist"), }, resolve: { extensions: [".js", ".vue", ".json", ".ts"], alias: { "@": path.join(__dirname, "./src"), }, }, // ... module: { rules: [ // ... { test: /\.(ts)$/, loader: "ts-loader", exclude: /node_modules/, options: { appendTsSuffixTo: [/\.vue$/], }, }, // ... ], }, // ... }; 每日一题 https://github.com/WindrunnerMax/EveryDay 参考 https://juejin.cn/post/6989491439243624461 https://juejin.cn/post/6844903942736838670 https://segmentfault.com/a/1190000012789253

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwzzpz.html