vue-cli早期版本支援搭建時直接引入typescript,不需要自己配置
3.4.1版本ui搭建時沒有自動整合typescript,所以記錄下自己搭建的坑
總共三步
第一步:vue.config.js配置loader,涉及兩個依賴ts-loader,typescript
chainWebpack: config => {
config.module
.rule('tsx')
.use('ts-loader')
.loader('ts-loader')
.tap(options => {
return Object.assign(options || {}, { allowTsInNodeModules: true });
})
}
複製程式碼
第二步:cli3不能手動修改entry,需要安裝一個外掛@vue/cli-plugin-typescript
yarn add @vue/cli-plugin-typescript
複製程式碼
第三步:根目錄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/**/*"
],
"exclude": [
"./node_modules/*",
"./public/*"
]
}
複製程式碼
好了,配置檔案已經搞定,可以開始寫ts了
<script lang="ts">
import HelloWorld from './components/HelloWorld.vue';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
@Component<Vue>({
components: {
HelloWorld
}
})
export default class App extends Vue {
public name:string = 'app';
}
</script>
複製程式碼
其他工具
<template lang="pug">
<style scoped lang="scss">
yarn add pug
yarn add pug-plain-loader
yarn add sass-loader
yarn add node-sass
複製程式碼
配置sass變數及postcss pxtorem
css: {
modules: true,
loaderOptions: {
sass: {
data: `@import "@/variables.scss";`
},
postcss: {
plugins: [
require('postcss-pxtorem')({
rootValue: 75,
propList: ['*', '!font-size'],
}),
]
}
}
}
複製程式碼
如何打包多頁應用
熟悉webpack的同學知道多頁打包主要是宣告多個entry,vue-cli3配置有點不一樣的是,需要指定pages
let path = require('path')
let glob = require('glob')
function getEntry(globPath) {
let pages = {};
glob.sync(globPath).forEach(function(entry) {
let basename = path.basename(entry, path.extname(entry));
pages[basename] = {
entry: entry,
template: 'public/index.html',
filename: `${basename}.html`,
chunks: [basename]
}
});
return pages;
}
// vue.config.js下面export增加pages屬性
pages: getEntry('./src/pages/*.ts'),
複製程式碼
上面程式碼將會產出
pages: {
login: {
entry: './src/pages/login.ts',
template: 'public/index.html',
filename: 'login.html',
chunks: ['login']
},
main: {
entry: './src/pages/main.ts',
template: 'public/index.html',
filename: 'main.html',
chunks: ['main']
}
}
複製程式碼
打包之後的檔案目錄如下:
多頁打包的另一個問題是:本地伺服器以哪個頁面為入口?
// 所以需要做個配置
devServer: {
index: 'main.html'
}
複製程式碼
其他配置項可以參考vue-cli3官網
cli.vuejs.org/zh/guide/