################typescript webpack###############
npm i typescript ts-loader --save-dev
tsconfig.json使用的时候需要在根目录下创建 配置ts
常用的选项 compilerOptions
#############webpack ts 初始化 tsconfig.json###############
根目录
node_modules
src
app.ts
package.json
tsconfig.json
webpack.config.js
npm init
npm i webpack typescript ts-loader --save-dev
根目录下创建 tsconfig.json 内容如下
{
'compilerOptions':{
'module':'commonjs',
'target':'es5', 编译后的文件是在什么环境下运行的
'allowJs':true,
'typeRoots':[ 这里是设置引用声明文件的路径
'./node_modules/@type' 使用npm install @types/lodash 安装的声明文件所在的位置
'./typings/modules' 使用typings install lodash --save 安装的声明文件所在的位置
]
},
'include':[
'./src/*'
],
'exclude':['./node_modules']
}
根目录下创建 webpack.config.js
module.exports = {
entry:{'app':'app.ts'},
output:{filename:'[name].bundle.js'},
module:{
rulse:[
{
test:/\.tsx?$ /,
use:{
loader:'ts-loader'
}
}
]
}
}
src下创建 app.ts npm i lodash -s
import * as _ from 'lodash'
console.log(_.chunk([1,2,3,4,5],2))
const NUM= 45
interface Cat{ ts语法 Cat类型
name:String,sex:String
}
function touchCat(cat: Cat) {
console.log('喵喵喵!!!',cat.name)
}
touchCat({
name:'tom'
sex:'male'
})
#############webpack ts 声明文件###############
npm install @types/lodash
npm install @types/vue
ts 中类型判断
引入的类库 也是有相应的申明文件
有了错误 及时反馈 如下:
import * as _ from 'lodash'
console.log(_.chunk([1,2,3,4,5,6],2)) 正确的参数设置
npm install @types/lodash
console.log(_.chunk(2)) 错误的参数设置
如果没有npm i 安装声明文件化是不会报错的。
还有一种方式是:
npm install typings -g 全局安装上之后可以在项目里在局部安装类型声明
typings install lodash --save 安装在本地项目里 在根目录下会多出来 typings.json和typings目录(类似node_modules)
npm uninstall @types/lodash --save 删除本地项目里安装的 声明文件
但是使用这钟方式需要手动配置 tsconfig.json 来使用它
'compilerOptions':{
'module':'commonjs',
'target':'es5', 编译后的文件是在什么环境下运行的
'allowJs':true,
'typeRoots':[ 这里是设置引用声明文件的路径
'./node_modules/@type' 使用npm install @types/lodash 安装的声明文件所在的位置
'./typings/modules' 使用typings install lodash --save 安装的声明文件所在的位置
]
},