如何使用Rollup.js捆绑JavaScript文件

如何使用Rollup.js捆绑JavaScript文件

在本教程中,我们将了解如何使用rollup.js捆绑JavaScript文件。在开始之前,首先要熟悉JavaScript模块打包工具 Rollup ,它将多个源文件编译成一个单独的捆绑包。Rollup与webpack和Browserify类似。由于即使将它们捆绑到一个单元中,Rollup仍能使文件保持较小的能力,因此比许多其他打包工具更受欢迎。

Rollup具有多个功能,其中一些如下所述:

  • 当您使用较小且自包含的源文件时,开发更易于管理。

  • 在捆绑过程中,源代码可以轻松美化,lint并进行语法检查。

  • 摇树也有助于删除未使用的函数。

  • 我们甚至可以进行向后兼容的ES5转译。

  • 还可以去除日志,甚至可以对生产捆绑包进行缩小。

现在,我们对Rollup的作用有了一个基本的了解,让我们首先创建一个简单的JavaScript项目。

假设我们有一个名为“rest-api-example”的项目,其目录结构如下所示:

├── controller
│  └── books.js
├── package-lock.json
├── package.json
├── routes
   └── books.js
└── src
   ├── index.js

3 directories, 5 files

我们可以看到我们有多个文件和目录,我们需要关注的唯一文件是“src”目录中的“index.js”文件。

index.js

这个index.js文件是我们将尝试使用Rollup.js以不同的格式捆绑的文件。下面是index.js文件的代码。

// to require the framework
const app = require('fastify')({
   logger: true
})

app.addHook('onRoute', (routeOptions) => {
   console.log(`Routes that are registered are: {routeOptions.url}`)
})

// to declare a single route
app.get('/', function (req, reply) {
   reply.send({
      Welcome: 'TutorialsPoint'
   })
})

// Register routes to handle blog posts
const bookRoutes = require('../routes/books')
bookRoutes.forEach((route, index) => {
   app.route(route)
})

// Run the server!
app.listen(3000, (err, address) => {
   if (err) {
      app.log.error(err)
      process.exit(1)
   }
   app.log.info(`The server is listening on{address}`)
})

在这段代码中,我们可以看到我们使用了常见的JavaScript箭头函数和基本语法。

将Rollup作为依赖项安装

假设我们想要使用Rollup.js来打包这个JavaScript文件。为了做到这一点,我们首先需要将Rollup作为一个依赖项安装到我们的项目中。

以下命令将在您的项目中安装Rollup。

npm install --save-dev rollup

package.json

运行上述命令后,我们应该在”package.json”文件中看到rollup的依赖项。下面是我项目的”package.json”文件的内容供参考。

{
   "name": "fastify-rest-api",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
      "test": "echo "Error: no test specified" && exit 1"
   },
   "keywords": [],
   "author": "",
   "license": "ISC",
   "dependencies": {
      "fastify": "^4.2.1"
   },
   "devDependencies": {
      "rollup": "^2.77.0"
   }
}

rollup.config.js

安装了Rollup之后,下一步是在与我们的”package.json”文件位于同一根目录的位置创建一个新文件,并将该文件命名为 rollup.config.js

注意 − Rollup配置文件的确切名称应该是这样的。

下面显示的代码片段是我的rollup.config.js文件。

export default {
   input: 'src/index.js',
   output: {
      file: 'src/main.min.js',
      : 'cjs',
   }
};

在上面的代码片段中,我们使用了不同的属性。让我详细解释一下每个属性。

  • 输入 - 在这个字段中,我们提供要Rollup的文件的名称。在大多数情况下,这个文件将是主要的JavaScript文件,它基本上启动了您的项目。

  • 输出 - 上述config.js文件中使用的输出对象包含两个属性,即file和format,其中file包含将作为Rollup输出创建的文件的名称,format字段包含我们希望Rollup的值作为格式类型的值。

在我们的config.js中,我们只是简单地表示我们希望在Rollup完成时将一个”cjs”文件作为输出。

开始Rollup.js

为了实际开始Rollup和测试它,我们需要在终端中运行以下命令。

./node_modules/.bin/rollup -c

运行上述命令后,我们将在终端中获得以下 输出。

src/index.js → src/main.min.js...
created src/main.min.js in 13ms

请注意,编译时间会因机器不同而有所不同。现在,如果我们检查目录结构,应该是这样的。

├── controller
│  └── books.js
├── package-lock.json
├── package.json
├── rollup.config.js
├── routes
│  └── books.js
└── src
   ├── index.js
   └── main.min.js

main.min.js

在上面的树形结构中,我们可以看到一个名为”main.min.js”的新文件被创建了。打开文件,它应该和下面显示的文件完全一样。

'use strict';

// to require the framework
const app = require('fastify')({
   logger: true
});

app.addHook('onRoute', (routeOptions) => {
   console.log(`Routes that are registered are: {routeOptions.url}`);
});

// to declare a single route
app.get('/', function (req, reply) {
   reply.send({
      Welcome: 'TutorialsPoint'
   });
});

// Register routes to handle blog posts
const bookRoutes = require('../routes/books');
bookRoutes.forEach((route, index) => {
   app.route(route);
});

// Run the server!
app.listen(3000, (err, address) => {
   if (err) {
      app.log.error(err);
      process.exit(1);
   }
   app.log.info(`The server is listening on{address}`);
});

您可以很容易地注意到Rollup之前和之后文件大小的差异。

在上一个示例中,我们将其转换为常见的JavaScript格式,正如我们在rollup.config.js文件的output对象的format属性中提到的。

假设我们希望将打包的JS文件的格式设置为iife。为此,我们可以在rollup.config.js文件中更改格式。

rollup.config.js

考虑下面的更新后的rollup.config.js文件。

export default {
   input: 'src/index.js',
   output: {
      file: 'src/main.min.js',
      format: 'iife',
   }
};

注意,我们只需要在rollup.config.js文件中更改format字段的值,就可以完成所有设置。

为了实际打包文件,我们需要运行下面显示的命令:

./node_modules/.bin/rollup -c

输出

一旦我们运行上述命令,就会在终端中得到以下输出:

src/index.js → src/main.min.js...
created src/main.min.js in 16ms

现在我们打开”main.min.js”文件,它将以IIFE格式显示。

(function () {
   'use strict';

   // to require the framework
   const app = require('fastify')({
      logger: true
   });

   app.addHook('onRoute', (routeOptions) => {
      console.log(`Routes that are registered are: {routeOptions.url}`);
   });

   // to declare a single route
   app.get('/', function (req, reply) {
      reply.send({
         Welcome: 'TutorialsPoint'
      });
   });

   // Register routes to handle blog posts
   const bookRoutes = require('../routes/books');

   bookRoutes.forEach((route, index) => {
      app.route(route);
   });

   // Run the server!
   app.listen(3000, (err, address) => {
      if (err) {
         app.log.error(err);
         process.exit(1);
      }
      app.log.info(`The server is listening on{address}`);
   });
})();

可以清晰地看到该文件是以IIFE格式编写的。

结论

在本教程中,我们学习了如何使用Rollup.js将JavaScript文件捆绑成更小的大小和我们所偏好的格式。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程