解决 rollup-plugin-typescript2 编译速度缓慢问题

5,328 阅读1分钟

使用 rollup 打包组件时会用到ts。为了生成声明文件方便就直接使用 rollup-plugin-typescript2 这个插件。

但是用着用着就会变得很慢...

解决方法就是直接不使用它。 😂

替换方案如下:

1、 在babel插件的 presets 配置选项中加入 typescript

   //...
   presets: [ 
        ["@babel/typescript", {
            allowDeclareFields: true
        }], 
     	//...
    ], 
    

2、 写一个rollup插件用以生成声明文件

思路:监听构建结束,然后使用 tsc 命令直接声明描述文件

//插件源码  emitDeclaration.js

const chalk = require('react-dev-utils/chalk');
const ts = require("typescript");
let tsHost;

//利用tsc生成 d.ts文件
export default function emitDeclaration() {
    let firseBuild = true;
const production = !process.env.ROLLUP_WATCH; 

    // 开启tsc监听
    const startEmit = () => {
          const formatHost = {
              getCanonicalFileName: (path) => path,
              getCurrentDirectory: ts.sys.getCurrentDirectory,
              getNewLine: () => ts.sys.newLine,
          };

            function watchMain() {
                    const configPath = ts.findConfigFile(/*searchPath*/ "./", ts.sys.fileExists, "tsconfig.json");
                    if (!configPath) {
                            throw new Error("Could not find a valid 'tsconfig.json'.");
                    }

                    const origCreateProgram = host.createProgram;
                    host.createProgram = (rootNames, options, host, oldProgram) => {
                            console.log("** 即将创建 ts 监听进程! **");
                            return origCreateProgram(rootNames, options, host, oldProgram);
                    };
                    const origPostProgramCreate = host.afterProgramCreate;

                    host.afterProgramCreate = (program) => {
                            console.log("** 即将创建 ts 监听进程完毕! **");
                            origPostProgramCreate(program);
                    };

                    tsHost = ts.createWatchProgram(host);
            }

                function reportDiagnostic(diagnostic) {
                        console.error(chalk.red("Error", diagnostic.code, ":", ts.flattenDiagnosticMessageText(diagnostic.messageText, formatHost.getNewLine())));
                }

                function reportWatchStatusChanged(diagnostic) {
                        console.info();
            console.error(chalk.cyan(ts.formatDiagnostic(diagnostic, formatHost)));
                }

                watchMain();
    }

    const closeEmit = () => { 
        // 关闭子进程 
        tsHost && tsHost.close();
    }

    return {
        name: 'emit-declaration',
        buildEnd() { 
            firseBuild && startEmit();
            firseBuild = false;
            // 打包完成后在需要关闭 ts 进程
            production && closeEmit();
            return null;
        },
        closeWatcher() { 
            closeEmit()
        }
    };
}

3、 在rollup配置中引用插件

//rollup.config.js

import emitDeclaration from './emitDeclaration';

export default {
	//...
    
    plugins:[
    	 //放到最后就行,生成d.ts文件
    	emitDeclaration(),
    ]
}

4 修改 tsconfig.json

{
    //...
    compilerOptions:{  
      "outDir": "./dist/es",
      "allowJs": false,
      "declaration": true,
      "emitDeclarationOnly": true,
      "declarationDir": "dist/es",
      
      //...
    },
    exclude:[
    	"./dist/**/*" , //这个设置如果没有的话,tsc在生成文件时将发出一个错误
    ]
}

轻松搞定...

看完点赞,哈哈哈😁