什么是typescript
TypeScript 是 JavaScript的强类型版本。然后在编译期去掉类型和特有语法,生成纯粹的 JavaScript 代码。由于最终在浏览器中运行的仍然是 JavaScript,所以 TypeScript 并不依赖于浏览器的支持,也并不会带来兼容性问题。
TypeScript 是 JavaScript 的超集,这意味着他支持所有的 JavaScript 语法。并在此之上对 JavaScript 添加了一些扩展,如 class / interface / module 等。这样会大大提升代码的可阅读性。
与此同时,TypeScript 也是 JavaScript ES6 的超集,Google 的 Angular 2.0 也宣布采用 TypeScript 进行开发。这更是充分说明了这是一门面向未来并且脚踏实地的语言。
强类型语言的优势在于静态类型检查,具体可以参见 www.zhihu.com/question... 的回答。概括来说主要包括以下几点:
1.静态类型检查
2.IDE 智能提示
3.代码重构
4.可读性
1、首先vue-cli生成项目
这里复习一下我们的cli命令
vue init webpack 'projectName'
复制代码
2、安装ts支持
安装vue的官方插件
npm i vue-class-component vue-property-decorator --save
// ts-loader typescript 必须安装,其他的相信你以后也会装上的
npm i ts-loader typescript tslint tslint-loader tslint-config-standard --save-dev
复制代码
这些库大体的作用,可以按需引入:
vue-class-component:强化 Vue 组件,使用 TypeScript/装饰器 增强 Vue 组件
vue-property-decorator:在 vue-class-component 上增强更多的结合 Vue 特性的装饰器
ts-loader:TypeScript 为 Webpack 提供了 ts-loader,其实就是为了让webpack识别 .ts .tsx文件 tslint-loader跟tslint:我想你也会在.ts .tsx文件 约束代码格式(作用等同于eslint)
tslint-config-standard:tslint 配置 standard风格的约束
3、配置webpack
1、首先将main.js 修改为main.ts
2、修改webpack.base.conf.js
entry: {
app: './src/main.ts'
}
// TS后缀文件一如不用写后缀
resolve: {
extensions: ['.js', '.vue', '.json', '.ts'],
alias: {
'@': resolve('src')
}
}
// 如果创建项目的时候添加了eslint 还需要将 ...(config.dev.useEslint ? [createLintingRule()] : []),注释掉并添加如下代码
//添加ts文件解析
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/],
}
},
复制代码
3、对vue-loader.con.js作如下修改
//引入
const merge = require('webpack-merge')
并修改(添加tslint)
module.exports = {
loaders: merge(utils.cssLoaders({
sourceMap: sourceMapEnabled,
extract: isProduction
}),{
ts: ['ts-loader', 'tslint-loader']
}),
cssSourceMap: sourceMapEnabled,
cacheBusting: config.dev.cacheBusting,
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
复制代码
ts-loader 会检索当前目录下的 tsconfig.json 文件,根据里面定义的规则来解析.ts文件(就跟.babelrc的作用一样)
tslint-loader 作用等同于 eslint-loader
4、添加tsconfig.json完整配置请点击tsconfig.json
{
// 编译选项
"compilerOptions": {
// 输出目录
"outDir": "./output",
// 是否包含可以用于 debug 的 sourceMap
"sourceMap": true,
// 以严格模式解析
"strict": true,
// 采用的模块系统
"module": "esnext",
// 如何处理模块
"moduleResolution": "node",
// 编译输出目标 ES 版本
"target": "es5",
// 允许从没有设置默认导出的模块中默认导入
"allowSyntheticDefaultImports": true,
// 将每个文件作为单独的模块
"isolatedModules": false,
// 启用装饰器
"experimentalDecorators": true,
// 启用设计类型元数据(用于反射)
"emitDecoratorMetadata": true,
// 在表达式和声明上有隐含的any类型时报错
"noImplicitAny": false,
// 不是函数的所有返回路径都有返回值时报错。
"noImplicitReturns": true,
// 从 tslib 导入外部帮助库: 比如__extends,__rest等
"importHelpers": true,
// 编译过程中打印文件名
"listFiles": true,
// 移除注释
"removeComments": true,
"suppressImplicitAnyIndexErrors": true,
// 允许编译javascript文件
"allowJs": true,
// 解析非相对模块名的基准目录
"baseUrl": "./",
// 指定特殊模块的路径
"paths": {
"jquery": [
"node_modules/jquery/dist/jquery"
]
},
// 编译过程中需要引入的库文件的列表
"lib": [
"dom",
"es2015",
"es2015.promise"
]
}
}
<!--以下是我的配置------------------------------->
{
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
],
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"allowJs": true,
"module": "esnext",
"target": "es5",
"moduleResolution": "node",
"isolatedModules": true,
"lib": [
"dom",
"es5",
"es2015.promise"
],
"sourceMap": true,
"pretty": true
}
}
复制代码
5、添加tslint.json
{
"extends": "tslint-config-standard",
"globals": {
"require": true
}
}
复制代码
6、让ts识别.vue文件
由于 TypeScript 默认并不支持 *.vue 后缀的文件,所以在 vue 项目中引入的时候需要创建一个 vue-shim.d.ts 文件,放在项目项目对应使用目录下,例如 src/vue-shim.d.ts
//告诉ts .vue文件交给vue处理
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
//将html识别为字符串
declare module "*.html" {
let template: string;
export default template;
}
复制代码
而在代码中导入 *.vue 文件的时候,需要写上 .vue 后缀。原因还是因为 TypeScript 默认只识别 *.ts 文件,不识别 *.vue 文件:
至此vue-cli引入ts已经介绍完毕
参考 vue + typescript 新项目起手式
Vue全家桶+TypeScript使用总结
你以为结束了?
ts需要webpack4.x的支持,我们通过vue-cli2.x创建的项目默认使用webpack3.6.0 所以我们还需要升级我们项目的webpack版本
1、首先
npm i webpack-cli@2.0.15 webpack@4.6.0 css-loader@0.28.11 extract-text-webpack-plugin@4.0.0-beta.0 file-loader@1.1.11 html-webpack-plugin@3.2.0 optimize-css-assets-webpack-plugin@4.0.0 url-loader@1.0.1 vue-loader@15.0.3 vue-style-loader@4.1.0 vue-template-compiler@2.5.16 webpack-bundle-analyzer@2.11.1 webpack-dev-middleware@3.1.3 webpack-dev-server@3.1.3 webpack-hot-middleware@2.22.1 compression-webpack-plugin@1.1.11 -D
复制代码
2、再次
npm i eslint@4.19.1 eslint-config-standard@11.0.0 eslint-friendly-formatter@4.0.1 eslint-loader@2.0.0 eslint-plugin-import@2.11.0 eslint-plugin-node@6.0.1 eslint-plugin-promise@3.7.0 eslint-plugin-standard@3.1.0 eslint-plugin-vue@4.5.0 -D
复制代码
3、然后
// webpack.base.conf.js
const { VueLoaderPlugin } = require('vue-loader')
module.exports = {
// ...
plugins: [
new VueLoaderPlugin()
]
}
复制代码
4、分别对开发环境和生产环境添加mode
mode: 'development'
mode: 'production'
复制代码
5、开发环境去掉webpack4.x默认有该配置
new webpack.NamedModulesPlugin()
new webpack.NoEmitOnErrorsPlugin()
复制代码
6、将生产环境下面的commonschunkplugin插件配置全部去掉
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
---------------------------------------------------------------------
// 添加
optimization: {
runtimeChunk: {
name: 'manifest'
},
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all'
},
'async-vendors': {
test: /[\\/]node_modules[\\/]/,
minChunks: 2,
chunks: 'async',
name: 'async-vendors'
}
}
}
}
复制代码
7、npm run build 又会出错 将webpack.prod.conf.js作如下修改
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
allChunks: true
}),
//改为
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[md5:contenthash].css'),
allChunks: true
}),
复制代码
webpack升级参考vue-cli#webpack3.0升级到webpack4.6