三种方式处理
- babel-loader 编译ts (@babel/preset-typescript)
- ts-loader
- tsc
1. babel-loader 通过babelrc文件配置 @babel/preset-typescript 处理ts
以webpack为例
// webpack配置
{
test: /\.tsx?$/,
loader: "babel-loader",
exclude: /node_modules/,
},
// babel.config.js
module.exports = {
presets: [
[
"@babel/preset-env",
],
"@babel/preset-react",
"@babel/preset-typescript",
],
plugins: [["@babel/plugin-transform-runtime"]],
};
rollup使用@rollup/plugin-babel 插件使用 @babel/preset-typescript编译ts
import babel from "@rollup/plugin-babel";
const extensions = ["*", ".js", ".ts"]
export default {
input: "./src-ts/index.ts", // 表示以哪个文件作为打包的入口
output: {
file: "dist/dist-ts/ts-vue.js",
name: "TsVue", // 指定打包后全局变量的名字 (会在全局上增加一个Vue属性) global.Vue
format: "umd", // 表示统一模块规范 esm,cjs,iife, umd(统一模块规范 cjs+amd)
sourcemap: true, // 将es6转化为es5后的源码调试 (希望可以调试)
},
plugins: [
babel({
// 不会走babelrc文件
babelrc: false,
extensions,
exclude: "node_modules/**",
presets: [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript",
],
}),
],
};
rollup使用@rollup/plugin-typescript编译typescript
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
export default {
input: "./src-ts/index.ts", // 表示以哪个文件作为打包的入口
output: {
file: "dist/umd/ts-vue.js",
name: "TsVue", // 指定打包后全局变量的名字 (会在全局上增加一个Vue属性) global.Vue
format: "umd", // 表示统一模块规范 esm,cjs,iife, umd(统一模块规范 cjs+amd)
sourcemap: true, // 将es6转化为es5后的源码调试 (希望可以调试)
},
plugins: [
resolve(),
commonjs(),
typescript(),
],
};
2. 使用ts-loader
以webpack为例
// webpack.config.js
const path = require("path");
module.exports = {
entry: "./src/index.ts",
output: {
path: path.join(__dirname, "/dist"),
publicPath: "/",
filename: "index.js",
library: "myNpm",
libraryTarget: "umd",
libraryExport: "default",
},
resolve: {
extensions: [".ts", ".tsx", ".json", ".js"],
},
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: "ts-loader",
// options: {
// // 指定特定的ts编译配置,为了区分脚本的ts配置
// configFile: path.resolve(__dirname, "./tsconfig.json"),
// },
},
],
exclude: /node_modules/,
},
{
test: /\.js?$/,
loader: "babel-loader",
exclude: /node_modules/,
},
],
},
// ...
};
3. tsc对文件进行编译
npm install typescript --save-dev
package.json scripts 添加如下命令, 通过tsc编译ts文件
"scripts": {
"tsc:types": "tsc -p tsconfig.json --emitDeclarationOnly --outDir tsc-types",
"tsc:esm": "tsc --project tsconfig.json --module es2015 --outDir tsc-esm",
"tsc:cjs": "tsc --project tsconfig.json --outDir tsc-cjs",
"ts-check": "tsc -p tsconfig.json --noEmit",
}
网友评论