一、创建项目
1、首先利用CLI创建,首先cmd到想创建的文件夹下,vue create v3tset。这部分和vue2一样。
坑1:创建完以后进入项目run serve的时候会报一个错:Cannot find module
‘vue-loader-v16/package.json’。 这是因为不能科学上网导致有些东西没下载下来。 先npm uninstall vue-loader-v16
卸载,再cnpm i vue-loader-v16
镜像安装就行了
添加cfg配置,项目的根目录创建文件:vue.config.js
// vue.config.js
// 详细配置参考https://cli.vuejs.org/zh/config/
module.exports = {
outputDir: 'dist', // 打包的目录
lintOnSave: true, // 在保存时校验格式
productionSourceMap: false, // 生产环境是否生成 SourceMap
devServer: {
open: true, // 启动服务后是否打开浏览器
overlay: { // 错误信息展示到页面
warnings: true,
errors: true
},
host: '0.0.0.0',
port: 333, // 服务端口
https: false,
hotOnly: false,
// proxy: { // 设置代理
// '/api': {
// target: host,
// changeOrigin: true,
// pathRewrite: {
// '/api': '/',
// }
// },
// },
},
}
2、还有一种是利用vite创建,同上cmd到想创建的文件夹下,npm init vite-app v3vite。
添加cfg配置,项目的根目录创建文件:vite.config.js
// vite.config.js
module.exports = {
port: 8077, // 服务端口
proxy: { // 代理
// string shorthand
"/foo": "http://localhost:4567/foo",
// with options
"/api": {
target: "http://jsonplaceholder.typicode.com",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
};
3、添加TypeScript
自动添加:cli限定,命令vue add typescript
手动添加:安装依赖 npm install typescript -D
根目录创建 tsconfig.json 文件:
// tsconfig.json
{
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
],
"exclude": [
"node_modules"
],
"compilerOptions": {
// 与 Vue 的浏览器支持保持一致
"target": "es5",
// 如果使用 webpack 2+ 或 rollup,可以利用 tree-shake:
"module": "es2015",
// 这可以对 `this` 上的数据 property 进行更严格的推断
"strict": true,
"moduleResolution": "node"
}
}
然后把 src 目录下的 main.js 文件名改为 main.ts,以及其他 js 文件改为 ts 后缀(config.js 改为 config.ts)
新建shims-vue.d.ts 放到 src 目录下,和 main.ts 平级
/* shims-vue.d.ts */
declare module '*.vue' {
import { defineComponent } from 'vue';
const component: ReturnType<typeof defineComponent>;
export default component;
}
修改app.vue文件为:
<script lang="ts">
import { defineComponent } from 'vue'
import HelloWorld from './components/HelloWorld.vue'
export default defineComponent({
name: 'App',
components: {
HelloWorld
}
})
</script>
修改根目录下的 index.html 文件,将 <script> 标签的 src 地址改为 "/src/main.ts"