请问一下编译ts是用@babel/preset-typescript
还是ts-loader
?我查了很多说babel7出来了就不需要用ts-loader
了,还有就是webpack
可以编译ts为什么还要用babel
来编译,就搞得我很头大...
主要就是有几个地方:
ts-loader
可以生成.d.ts
类型声明文件。webpack
还没找到相关方法,不过这个问题不大,大不了自己走一遍tsc
,主要还是编译过程中有问题。babel-loader
的test
是/\.js$/
还是/\.ts$/
,总感觉用什么都没有生效,因为两种打包的东西一开始就有一个箭头函数...
两种方法我试了,但是总还是不对,索性就把我的配置都贴上来了,请大佬看一下哪里出了问题,不是同时用!!!如果用ts-loader我就会把@babel/preset-typescript干掉,反之就把ts-loader干掉
// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: path.join(__dirname, '../source/bridge.ts'),
output: {
filename: 'bridge.[fullhash].js',
path: path.resolve(__dirname, '../lib'),
clean: true // 清空打包文件夹
},
resolve: {
extensions: ['.js', '.ts']
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'demo',
filename: 'index.html',
template: path.resolve(__dirname, '../demo/index.html')
})
]
};
// babel.config.json
{
"presets": [
[
"@babel/preset-env",
{
"modules": false
}
],
"@babel/preset-typescript"
],
"plugins": [
[
"@babel/plugin-transform-runtime",
{
"corejs": {
"version": 3,
"proposals": true
},
"useESModules": true
}
],
"@babel/proposal-class-properties",
"@babel/proposal-object-rest-spread",
]
}
// ts.config.json
{
"include": ["source/*.ts", "source/type.d.ts"],
"exclude": ["node_modules"],
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
"target": "ES5",
"module": "ESNext",
"lib": [
"ES2021",
"DOM",
"DOM.Iterable",
"ScriptHost"
],
"allowJs": true,
"isolatedModules": true,
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"declaration": true,
"sourceMap": true,
"outDir": "lib",
"rootDir": "source",
"allowSyntheticDefaultImports": true, // 当启用 esModuleInterop 时,将同时启用 allowSyntheticDefaultImports
"skipLibCheck": true, // 忽略所有的声明文件( *.d.ts)的类型检查
"forceConsistentCasingInFileNames": true,
"suppressImplicitAnyIndexErrors": true // 支持window[xxx]这种写法
}
}
看了眼
@babel/plugin-transform-typescript
的文档,文档里有说这个插件只支持语法,不支持类型检查,所以我觉得可能直接用 ts-loader 就行了。webpack 本身不能编译 ts,你要么用 babel-loader,要么用 ts-loader,要么用其它工具,比如 esbuild、swc。
webpack 会用
test
对应的 loader 处理对应的文件,至于你说的箭头函数,可能是目前的 preset-env target 配置就是支持箭头函数的。你可以在命令行里用npx browserslist
查看当前目标环境列表。