SuiteScript 2.1 Walkthrough: Node Polyfills with Webpack & stdlib

April 29, 2024 | 7 minute read
Mohammed Kassem
SuiteCloud Advocate
Text Size 100%:

In this guide, we'll focus on implementing the path module polyfill in SuiteScript 2.1. Next, we’ll walk you through setting up your project for effective polyfills integration and leveraging Webpack and stdlib to bridge functionality gaps. Finally, we’ll address key performance considerations when implementing polyfills by selectively using polyfills to extend functionality without excessively increasing the size of your build.

Node polyfills play a pivotal role in SuiteCloud projects, seamlessly integrating Node.js functionalities into the SuiteScript environment. This integration is crucial for enhancing capabilities like file operations, network communications, and server-side scripting—areas where SuiteScript's native functions may be limited. By incorporating Node polyfills, developers can significantly expand the range of functionalities within SuiteScript, pushing the boundaries of what's achievable in SuiteCloud projects.

Polyfills are pieces of code logic that fill in functionality gaps across different programming environments. They are particularly useful in implementing server-side Node.js features within client-side contexts, such as web browsers. In this integration process, tools like Webpack and stdlib are extremely helpful. Webpack streamlines the incorporation of these features, while stdlib provides a suite of additional utilities, ensuring a smooth and efficient operation of server-side features in SuiteScript applications.

Among various Node polyfills, the path and fs modules are especially valuable in the SuiteScript environment. These polyfills address specific Node.js functionalities often required in SuiteScript:

  • path:  Enhances file path management across different platforms within SuiteScript 2.1, streamlining directory and file handling processes.
  • fs (File System): Facilitates file reading and writing operations in non-server environments, broadening SuiteScript's file management capabilities.

Practical Integration of Node Polyfills in SuiteScript

Now, let’s review a practical application of Node polyfills in SuiteScript 2.1. One key area where polyfills demonstrate their utility is in file path management. Consider the example of the Node.js path module. This module is a classic case where a polyfill is not just useful but essential. It provides a streamlined way to handle file paths:

import path from 'path'
import file from 'N/file'

export function get(){
   const filePath = path.join('Document', 'report.csv’)
   file.load(filePath)
   //Additional processing...
}

In this code snippet, the path polyfill simplifies file path operations within SuiteCloud projects. It ensures that file paths are managed efficiently and consistently, reflecting the Node.js approach but within the constraints of the SuiteScript environment. This example highlights how the integration of Node polyfills can bridge the gap between the capabilities of Node.js and SuiteScript to enhance the functionality and user experience of SuiteCloud projects.

Using Webpack and stdlib in SuiteCloud Projects

Together, these tools form a robust framework that help SuiteScript developers create Node polyfills that bridge functionality gaps and extend their SuiteCloud project capabilities.

  • Webpack: Streamlines the inclusion and management of polyfills in a project by bundling polyfills along with other JavaScript files to ensure they are integrated and loaded where needed.
  • Webpack plug-ins: Certain Webpack plug-ins are designed to automatically detect and include the necessary polyfills in the build process. They simplify the integration of polyfills, ensuring that the correct versions are used and reducing manual configuration efforts.
  • stdlib: While stdlib itself isn't a polyfill, it complements the use of polyfills in projects by providing a broad range of additional functions and utilities. When used alongside polyfills, stdlib can fill in functionality gaps and extend the capabilities of JavaScript, especially in environments lacking certain native features.

Project Setup

  1. Update your package.json to include the necessary npm scripts:


   "scripts": {
       "build": "tsc",
       "webpack": "webpack"
   },

Notes:

  • The node-polyfill-webpack-plugin gives you access to multiple Node.js polyfills. To see them, click here.
  • We use TypeScript in this project to transpile TypeScript (.ts) to JavaScript (.js) using npm run build.
  1. In the project root folder, execute the following in your terminal to install the necessary build-time and runtime libraries for your project:
  • npm install @stdlib/stdlib
  • npm install @hitc/netsuite-types node-polyfill-webpack-plugin ts-loader typescript webpack webpack-cli --save-dev
  1. Configure TypeScript and Webpack. In your tsconfig.json, add the following:
    {

     "compilerOptions": {
       "module": "amd",
       "target": "ESNext",
       "sourceMap": false,
       "esModuleInterop": true,
       "experimentalDecorators": true,
       "noUnusedLocals": false,
       "moduleResolution": "node",
       "newLine": "LF",
       "baseUrl": ".",
       "lib": ["ESNext", "dom"],
       "paths": {
         "N": ["node_modules/@hitc/netsuite-types/N"],
         "N/*": ["node_modules/@hitc/netsuite-types/N/*"]
       },
       "outDir": "src/FileCabinet/SuiteScripts/"
     },
     "include": ["src/TypeScripts/*"],
     "exclude": ["node_modules"]
    }
  1. Now, create a src folder and a src > TypeScripts folder. This is where we’ll add our TypeScript SuiteScript 2.1 files.
  2. Create restletExample.ts in /src/TypeScripts/.
  3. Next, set up your webpack.config.js to manage the SuiteScript build process:

const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');

const webpack = require('webpack');

const path = require('path');

 

module.exports = {

 entry: './src/TypeScripts/restletExample.ts',

 output: {

   filename: 'restletExample.js',

   libraryTarget: 'amd',

   path: path.resolve(__dirname, "src/FileCabinet/SuiteScripts"),

 },

 module: {

   rules: [

     {

       test: /\.ts$/,

       use: 'ts-loader',

     },

   ],

 },

 externals: [/^N\//, /^N$/],

 externalsType: 'amd',

 optimization: {

   minimize: false

 },

 resolve: {

   extensions: ['.ts', '.js'],

 },

 plugins: [

   new webpack.BannerPlugin({

       banner: `/**

       * @NApiVersion 2.1

       * @NScriptType Restlet

       */

      `,

      raw: true

   }),

   new NodePolyfillPlugin()

 ]

};

Note:

  • The TypeScript entry, output, and modules are configured.
  • External modules are specified (beginning with 'N/') to align with SuiteScript standards.
  • NodePolyfillPlugin ensures Node.js compatibility.
  • BannerPlugin adds necessary SuiteScript annotations to the JavaScript output files when transpiled from TypeScript.
  1. Use stdlib in your SuiteScript 2.1 (.ts) files:
    With the setup complete, you can now import and use
    stdlib in your SuiteScript 2.1 files. For instance, access datasets like English month names:

import months from '@stdlib/datasets/month-names-en';

  1. monthNames = months();
  1. .log('Month Names:', monthNames);
  1. is a big library that has a ton of useful functions. Below is a table of useful utils that you may use in your SuiteCloud projects. For the full list, click here.

Feature

Description

Special Math Functions

150+ special math functions.

Probability Distributions

35+ probability distributions, with PDFs, CDFs, quantiles, moments, and more.

Pseudorandom Number Generators

40+ seedable PRNGs.

General Utilities

200+ utilities for data transformation, functional programming, and asynchronous control flow.

Assertion Utilities

200+ utilities for data validation and feature detection.

Sample Datasets

50+ datasets for testing and development.

Plot API

A plot API for data visualization and exploratory data analysis.

Important Considerations

When integrating Node polyfills into SuiteScript projects, it's crucial to weigh certain factors that could influence the overall performance and maintainability of your applications. Here are some key considerations to keep in mind:

  • Increased build size: Integrating Node polyfills can significantly increase the size of your application's build. This can lead to longer loading times and potentially impact the performance, especially in web environments.
  • Possibility of overhead: Not all polyfills are optimized for performance. Some might introduce unnecessary overhead, which could affect the efficiency and speed of the application.
  • Maintenance and update concerns: Relying on polyfills means keeping up with the latest updates and changes in the polyfill libraries. Failure to update regularly can lead to compatibility issues and maintaining them can be time-consuming.

Conclusion

Integrating Node polyfills with Webpack and stdlib in SuiteScript 2.1 significantly enhances our development capabilities within the SuiteCloud platform. This integration exemplified using the path module, demonstrates how we can overcome SuiteScript's limitations and align our development practices with modern standards.

The combination of Webpack and stdlib with Node polyfills enriches our development process, offering a more streamlined approach and an expanded set of functionalities. It's crucial, however, to remain mindful of the impact on build size, performance, and maintenance.

Embracing these tools and strategies not only advances our technical skills but also paves the way for creating more sophisticated and efficient SuiteCloud applications. Let’s continue to explore and integrate these innovations, pushing the limits of what we can achieve in SuiteScript development.

Mohammed Kassem

SuiteCloud Advocate


Previous Post

SuiteScript 2.1: Compatible Build-Time and Runtime Libraries

Mohammed Kassem | 9 min read

Next Post


Building real-time multi-cloud AI Microservices using TxEventQ, Sagas, True Cache in Oracle Database 23ai

Sanjay Goil | 10 min read