React的打包
要解析 react 的关键是解析 jsx
,所以除了安装 react
和react-dom
之外还要安装@babel/preset-react
插件。
cnpm install react react-dom --save
cnpm install --save-dev @babel/preset-react
TS版
有两个方案:
1)ts-loader ,typescript
2) @babel/preset-typescript
以第二个为例:
a. 先安装@babel/preset-typescript
包,它也是一个预设,再.babelrc
文件 中配置。
b. 在webpack配置文件中,配置loader。到这以及可以解析ts文件了,但是 代码可能不符合规范,所以还需第一个方案(下面这几步)。
c. 安装 typescript
,它的作用只是用来检验代码是不是符合规范。cnpm install typescript
;之后执行 npx typescript --init
生成一个ts配置文件 tsconfig.json
,这是你会发现你写的index.tsx一片报错,就说明其实第2)方案生成的文件就不是TS版本的。
d. 根据需要 安装 @types/react
、@types/react-dom
提示声明文件。
cnpm install @types/react @types/react-dom --save
e. 在tsconfig.json
文件中配置 "jsx": "react"
。
ts-loader 的配置 较为容易,这里说明了。
注:.tsx文件 是 ts + jsx(react),如果没有jsx则可以使用 .ts 文件。
// .babelrc文件
{
"presets": [
["@babel/preset-env",{
"useBuiltIns": "usage",
"corejs": 2
}],
"@babel/preset-react",
"@babel/preset-typescript" // 解析ts,转为js
],
}
// webpack.base.js
module: {
rules: [
{
test: /\.tsx?/,
use: ['babel-loader']
},
...
]
}
Vue的打包
1)先安装vue cnpm install vue --save
,配置loader。
2)建立 vue.shims.d.ts
文件,对.vue结尾模块进行说明。
3)对.vue文件中的 template 进行解析:cnpm install vue-loader vue-template-compiler --save-dev
,其中vue-template-compiler
就是用来解析 template 的,而vue-loader
是用来调用vue-template-compiler
插件的。
4)配置 loader 时还要 引入一个插件 let VueLoaderPlugin = require('vue-loader/lib/plugin')
才可以根据匹配文件 正常使用 。
// loader
{
test: /\.ts?/,
use: [
'babel-loader'
]
}
// index.ts
import Vue from 'vue'
import App from './App.vue' // 发现不识别该结尾的模块
let vm = new Vue({
el: "#root",
// render: h => h('h1',{},'helloworld')
render: h => h(App)
})
// vue.shims.d.ts
declare module "*.vue" { // 所有以.vue结尾的类型,叫做vue类型
import Vue from 'vue';
export default Vue
}
// 安装完 vue-loader 和 vue-template-compiler 后,配置loader
let VueLoaderPlugin = require('vue-loader/lib/plugin');
modules: {
rules: [
{
test: /\.vue$/,
use: [
"vue-loader"
]
},
...
]
}
plugins: [
new VueLoaderPlugin(),
...
]
vue中使用ts
1)安装 cnpm install vue-property-decorator --save
2) 在.babelrc
中配置 @babel/preset-typescript
<template>
<div>
Hello world
</div>
</template>
<script lang="ts"> // 还是会当为vue去解析,需要vue-property-decorator配置。
import {Component,Vue} from 'vue-property-decorator';
@Component({
components: {
// todo...
}
})
export default class Todo extends Vue {
public todos: string[] = ['a','b','c']
}
</script>
// .babelrc
["@babel/preset-typescript",{ // 解析ts,转为js
"allExtensions": true
}]