看啥推荐读物
专栏名称: Yzz
今天看啥  ›  专栏  ›  Yzz

利用 gulp 解决 rollup 中 typescript 与 babel 冲突

Yzz  · 掘金  ·  · 2019-09-14 12:46
阅读 25

利用 gulp 解决 rollup 中 typescript 与 babel 冲突

最近在用 lerna 重构一个项目,其中一个 package 是使用 rollup 作为脚手架的,需要使用 ts 对其进行重写,但是发现在使用 rollup 时,ts 只能被编译为 js,而之后却不能用 babel 编译为 es3.

首先明确 rollup 需要处理的任务流为

typescript = (rollup-plugin-typescript2) 
    	   => ES5 = (babel) 
           => ES3
复制代码

但是第一步、二步冲突,故采用 gulp 将上述任务拆分。

项目搭建

首先创建 rollup-repo 项目

mkdir rollup-repo && cd $_
复制代码

安装 gulp 两个工具在项目内

# 初始化项目
npm init
# 安装 gulp
npm install --save-dev gulp
复制代码

然后创建 gulpfile.js 脚本用于后续运行,并在文件中输入以下代码

const gulp = require ('gulp');

gulp.task ('build', async function () {
  console.log ('build');
});
复制代码

同时在 package.json 中添加 script,并在终端中输入 npm run build,看是否打印出 build

"scripts": {
    "build": "gulp build",
},
复制代码

引入 rollup

在项目中安装 rollup 用于打包 typescript

# 安装 rollup
npm install --save-dev rollup
复制代码

首先解决之前的第一个问题 typescript 转 ES2015

# rollup-plugin-tslint 用于检测 typescript
npm install --save-dev rollup-plugin-tslint
# rollup-plugin-typescript2 用于将 ts 编译为 js
npm install --save-dev rollup-plugin-typescript2
复制代码

将 rollup 处理 typescript 作为 gulp 的一个 task,使用 ./temp/index.js 作为中转的文件。更新 gulpfile.js 的内容如下

const {task, src, dest} = require ('gulp');
const {rollup} = require ('rollup');
const tslint = require ('rollup-plugin-tslint');
const typescript = require ('rollup-plugin-typescript2');
const tempFile = './temp.js';

task ('build', async function () {
  const bundleJS = await rollup ({
    input: 'index.ts',
    plugins: [tslint (), typescript ()],
  });

  await bundleJS.write ({
    file: tempFile,
    format: 'cjs',
  });
});
复制代码

在终端中运行命令 npm run build,此时发现在 tempFile 中,typescript 已经被编译为 ES2015 的代码,之后需要我们将它转换为 ES3

引入 gulp-babel 来处理这个任务

npm install --save-dev gulp-babel
复制代码

之后就是 gulp 很明显的 pipe 方式

const {task, src, dest} = require ('gulp');
const {rollup} = require ('rollup');
const tslint = require ('rollup-plugin-tslint');
const typescript = require ('rollup-plugin-typescript2');
const babel = require ('gulp-babel');
const tempFile = './temp.js';

task ('build', async function () {
  const bundleJS = await rollup ({
    input: 'index.ts',
    plugins: [tslint (), typescript ()],
  });

  await bundleJS.write ({
    file: tempFile,
    format: 'cjs',
  });

  src (tempFile)
    .pipe (
      babel ({
        presets: ['@babel/env'],
      })
    )
    .pipe (dest ('dist'));
});
复制代码

利用 babel 将 temp.js 中 ES2015 的代码编译为 ES3

至此,任务已经初步完成了,后续需要我们将 temp.js 删除并 uglyfly 代码

# clean file
npm install --save-dev gulp-clean
# uglyfly file
npm install --save-dev gulp-uglyfly
复制代码

引入两个插件来完成细化

src (tempFile)
    .pipe (
      babel ({
        presets: ['@babel/env'],
      })
    )
    .pipe (clean ())
    .pipe (uglyfly ())
    .pipe (dest ('dist'));
复制代码

结论

在这个脚手架的配置中主要是想利用 rollup 强大的 tree-shaking 功能,故将其结合在其中,可能会有更好的方法。




原文地址:访问原文地址
快照地址: 访问文章快照