vue旧项目升级到2.7后使用script setup语法,并使用pinia,支持typescript
以前使用vue2的项目已经老了,在新项目中习惯了script setup写法之后,已经不想在写老代码了,但是将vue2整体升级到vue3又很痛,刚好vue2的终极版本2.7.13整合了script setup的用法,可以很愉快的整合并开写script setup了,其中慢慢将vuex替换成pinia,到某一天,都换完了,就能直接install vue3,何不爽YY(前提是没有很多自定义的vue2内
·
前提:
以前使用vue2的项目已经老了,在新项目中习惯了script setup写法之后,已经不想在写老代码了,但是将vue2整体升级到vue3又很痛,刚好vue2的终极版本2.7.13整合了script setup的用法,可以很愉快的整合并开写script setup了,其中慢慢将vuex替换成pinia,到某一天,都换完了,就能直接install vue3,何不爽YY(前提是没有很多自定义的vue2内容,仅针对script setup和store的使用)。
准备工作:
1.安装依赖包
npm install
... vue@2.7.13
... vue-router@3.6.5
... pinia
npm install --save-dev
... @fullhuman/postcss-purgecss
... @fullhuman/vue-cli-plugin-purgecss
... @typescript-eslint/parser
... ts-loader@8.1.0 // 注意版本,要不然项目运行时可能会报错
2.修改文件
vue.config.js
modules.exports = { ... ... configureWebpack: { resolve: { extensions: ['.js', '.vue', '.json', '.ts', '.tsx'], // 添加 .ts 扩展名 }, module: { rules: [ { test: /\.ts(x?)$/, loader: 'ts-loader', exclude: /node_modules/, options: { appendTsSuffixTo: ['\\.vue$'], }, }, ], }, ... }
tsconfig.json
// tsconfig.json { "compilerOptions": { "target": "esnext", "module": "esnext", "strict": true, "jsx": "preserve", "importHelpers": true, "moduleResolution": "node", "experimentalDecorators": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "sourceMap": true, "baseUrl": ".", "types": [ "webpack-env" ], "paths": { "@/*": [ "src/*" ] }, "lib": [ "esnext", "dom", "dom.iterable", "scripthost" ] }, "include": [ "src/**/*.js", //src为本地开发目录 "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx" ], "exclude": [ "node_modules", "src/assets/lib/*" ], }
postcss.config.js
const IN_PRODUCTION = process.env.NODE_ENV === "production"; module.exports = { plugins: [ IN_PRODUCTION && require("@fullhuman/postcss-purgecss")({ content: [`./public/**/*.html`, `./src/**/*.vue`], defaultExtractor(content) { const contentWithoutStyleBlocks = content.replace( /<style[^]+?<\/style>/gi, "" ); return ( contentWithoutStyleBlocks.match( /[A-Za-z0-9-_/:]*[A-Za-z0-9-_/]+/g ) || [] ); }, safelist: [ /-(leave|enter|appear)(|-(to|from|active))$/, /^(?!(|.*?:)cursor-move).+-move$/, /^router-link(|-exact)-active$/, /data-v-.*/, ], }), ], };
src/shims-vue.d.ts
// shims-vue.d.ts declare module '*.vue' { import Vue from 'vue'; export default Vue; }
上面基本能满足基础编码的需要了,接下来开始改造一下原本的代码文件,我们继续
main.js
.... // 使用pinia import { createPinia, PiniaVuePlugin } from 'pinia'; .... .... .... Vue.use(PiniaVuePlugin); const pinia = createPinia(); pinia.use(StoreReset); .... .... const app = new Vue({ .... pinia, .... .... }); app.$mount('#app');
下面就是开始愉快的改在自己需要的store逻辑了。
改写老页面,可以开始用<script setup> 进行愉快的编码了。如果怕ts不好兼容,可以先不加lang='ts' 。
更多推荐
已为社区贡献1条内容
所有评论(0)