引言
项目使用的 Vue + TypeScript + webpack,其中TypeScript 使用的是ts-loader。
由于使用了vue的单文件组件,所以ts-loader配置了appendTsSuffixTo: [/\.vue$/] 。
但是发现在使用thread-loader和cache-loader加速构建时,会报Could not find file: '*.vue.ts'的错误。但是项目中并没有*.vue.ts的文件。
关于appendTsSuffixTo
官方文档给出的解释:appendTsxSuffixTo
A list of regular expressions to be matched against filename. If filename matches one of the regular expressions, a .ts or .tsx suffix will be appended to that filename.
This is useful for *.vue file format for now. (Probably will benefit from the new single file format in the future.)。
大致意思是,会给对应文件添加个.ts或.tsx后缀。这也就是报错的找不到vue.ts的由来。
让我们来梳理下ts编译vue 单文件组件的过程:
vue 单文件组件中假如使用了
lang="ts",ts-loader需要配置appendTsSuffixTo: [/\.vue$/],用来给.vue文件添加个.ts后缀用于编译。
但是这个.ts文件并不实际存在,所以在使用cache-loader时,会报找不到这个文件的错误。
解决方案
由于报的是找不到文件错误,那我们就把 TypeScript代码 从 .vue中移出来。
使用一个单独的ts文件,然后vue在引用这个ts文件。
xxx.vue文件:
<template>
<div>
</div>
</template>
<script lang="ts" src="./xxx.ts"></script>
<style>
</style>
xxx.ts文件:
export default {
}
加速TypeScript构建
ts-loader默认没有增量编译,并且单线程,直接进行类型检查。这会导致TypeScript的编译过程非常慢。
我们可以使用awesome-typescript-loader或者thread-loader/happypack+hard-source-webpack-plugin/cache-loader+ts-loader+fork-ts-checker来加速编译。
注意:这几种方式都需要将TypeScript代码从.vue文件中移出来。
ts-loader组合
thread-loader/happypack是进行多线程/进程编译,可充分利用多核cpu。 hard-source-webpack-plugin/cache-loader是记录编译缓存,编译增量编译。ts-loader进行 TypeScript编译。fork-ts-checker单独线程/进程进行错误检查。
var ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = {
context: __dirname, // to automatically find tsconfig.json
devtool: 'inline-source-map',
entry: './src/index.ts',
output: { filename: 'dist/index.js' },
module: {
rules: [{
test: /\.tsx?$/,
use: [
{ loader: 'cache-loader' },
{
loader: 'thread-loader',
options: {
// there should be 1 cpu for the fork-ts-checker-webpack-plugin
workers: require('os').cpus().length - 1,
},
},
{
loader: 'ts-loader',
options: {
happyPackMode: true // IMPORTANT! use happyPackMode mode to speed-up compilation and reduce errors reported to webpack
}
}
]
}]
},
resolve: {
extensions: ['.ts', '.tsx', 'js']
},
plugins: [
new ForkTsCheckerWebpackPlugin({ checkSyntacticErrors: true })
]
};
awesome-typescript-loader
awesome-typescript-loader等同于ts-loader组合。
{
test: /\.ts$/,
// loader: 'ts-loader',
// 使用`awesome-typescript-loader`编译`TypeScript`
loader:'awesome-typescript-loader'
}
帮助:
awesome-typescript-loader
happypack例子
thread-loader例子
参考
注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。