Create a Web Application Using the Oracle JET Command-Line Interface

Use the Oracle JET command-line interface (CLI) to create, build, and serve web applications that run in desktop and mobile browsers.

Before you can create your first Oracle JET web application using the CLI, you must also install the prerequisite packages if you haven’t already done so. For details, see Install Oracle JET Tooling.

Note:

You can also use the tooling to create hybrid mobile applications. For additional information, see Understanding the Hybrid Mobile Application Workflow.

Scaffold a Web Application

Use the Oracle JET command-line interface (CLI) to scaffold an application that contains a blank template or one pre-configured Starter Template with a basic layout, navigation bar, or navigation drawer. Each Starter Template is optimized for responsive web or hybrid mobile applications. Additionally, Starter Templates support TypeScript development should you wish to create your application in TypeScript. After scaffolding, you can modify the application as needed.

To scaffold an Oracle JET web application:
  1. At a command prompt, enter ojet create with optional arguments to create the Oracle JET application and scaffolding.
    ojet create [directory]
                [--template={template-name:[web|hybrid]|template-url|template-file}] 
                [--typescript]
                [--help]

    Tip:

    You can enter ojet help at a terminal prompt to get additional help with the Oracle JET CLI.

    For example, the following command will create a web application in the web-app-navbar directory using the web version of the navbar template:

    ojet create web-app-navbar --template=navbar

    To scaffold the web application using the same Starter Template but with support for TypeScript development, add the --typescript argument to the command:

    ojet create web-app-navbar --template=navbar --typescript

    To scaffold the web application with the hybrid mobile version of the navbar template, enter the following command:

    ojet create web-app-navbar --template=navbar:hybrid
  2. Wait for confirmation.

    The scaffolding will take some time to complete. When successful, the displays:

    Oracle JET: Your app is ready! Change to your new app directory web-app-navbar and try ojet build and serve...
  3. In your development environment, update the code for your application.

    Tip:

    If you selected the blank template during scaffolding, you can still follow the same process to add cookbook samples or other content to your application. However, it will be up to you to create the appropriate view templates or viewModel scripts.

About ojet create Command Options for Web Applications

Use ojet create with optional arguments to create the Oracle JET web application and scaffolding.

The following table describes the available ojet create command options and provides examples for their use.

Option Description

directory

Application location. If not specified, the application is created in the current directory. The directory will be created during scaffolding if it doesn’t already exist.

template

Template to use for the application. Specify one of the following:

  • template-name

    Predefined template. You can enter blank, basic, navbar or navdrawer . Defaults to blank if not specified.

    Optionally, add :web or :hybrid to the template name to specify web or hybrid mobile styling. By default template will use the web styling, but you can add :hybrid to change the styling to hybrid mobile, typically basic:hybrid, navbar:hybrid or navdrawer:hybrid.

  • template-URL

    URL to zip file containing the name of a zipped application: http://path-to-app/app-name.zip.

  • template-file

    Path to zip file on your local file system containing the name of a zipped application: "path-to-app/app-name.zip". For example:
    --template="C:\Users\SomeUser\app.zip"
    --template="/home/users/SomeUser/app.zip"
    --template="~/projects/app.zip"

    If the src folder is present in the zip file, then all content will be placed under the src directory of the application, except for the script folder which remains in the root. If no src folder is present, the contents of the zip file will be placed at the root of the new application.

help

Displays a man page for the ojet create command, including usage and options: ojet create --help.

About Scaffolding a Web Application

Scaffolding is the process you use in the Oracle JET command-line interface (CLI) to create an application that contains a blank template or one pre-configured with a basic layout, navigation bar, or navigation drawer. Each pre-configured template is optimized for responsive web or hybrid mobile applications. After scaffolding, you can modify the application as needed.

The following image shows the differences between the pre-configured Starter Templates. The blank template contains an index.html file but no UI features. The basic:web template is similar to the blank template but adds responsive styling that will adjust the display when the screen size changes. The navbar:web and navdrawer:web templates contain sample content and follow best practices for layout, navigation, and styling that you can also modify as needed.

Note:

Do not confuse the basic template which contains no content with the Oracle JET QuickStart Basic application available in NetBeans 8.2 examples. The NetBeans application uses the navdrawer:web layout shown above and contains the same sample content.

If you want your web application to look more like a mobile application, you can scaffold your web application with a hybrid mobile version of the basic, navbar, or navdrawer template: basic:hybrid, navbar:hybrid, or navdrawer:hybrid.

After scaffolding, you can perform the following tasks to customize your application:

About the Web Application File Structure

The Oracle JET scaffolding process creates files and folders that you modify as needed for your application.

The new application will have a directory structure similar to the one shown in the following image.

The application folders contain the application and configuration files that you will modify as needed for your own application.

Directory or File Description

node_modules

Contains the Node.js modules used by the tooling.

scripts

Contains the oraclejet-build.js and oraclejet-serve.js files that you can modify to customize standard Oracle JET build and serve steps for your application. See Customize the Web Application’s Build Steps and Customize the Web Application’s Serve Steps.

Also contains template hook scripts that you can modify to define new build and serve steps for your application. See Customize the Web Application Tooling Workflow

src

Site root for your application. Contains the application files that you can modify as needed for your own application and should be committed to source control.

The content will vary, depending upon your choice of template. Each template, even the blank one, will contain an index.html file and a main.js RequireJS bootstrap file.

Other templates may contain view templates and viewModel scripts pre-populated with content. For example, if you specified the navbar template during creation, the js/views and js/viewModels folders will contain the templates and scripts for a web application that uses a nav bar for navigation.

.gitignore

Defines rules for application folders to ignore when using a GIT repository to check in application source. Users who do not use a GIT repository can use ojet strip to avoid checking in content that Oracle JET always regenerates. Note this file must not be deleted since the ojet strip command depends on it.

oraclejetconfig.json

Contains the default source and staging file paths that you can modify if you need to change your application's file structure.

package.json

Defines npm dependencies and project metadata.

After scaffolding, you can perform the following tasks to customize your application:

Modify the Web Application’s File Structure

You can modify your scaffolded application’s file structure if the default structure doesn’t meet your needs.

The oraclejetconfig.json file in your application’s top level directory contains the default source and staging file paths that you can modify.

{
  "paths": {
    "source": {
      "common": "src",
      "web": "src-web",
      "hybrid": "src-hybrid",
      "javascript": "js",
      "styles": "css",
      "themes": "themes"
    },
    "staging": {
      "web": "web",
      "hybrid": "hybrid",
      "themes": "themes"
    }
  },
  "generatorVersion": "7.2.0"
}

To change the web application’s file structure:

  1. In your application’s top level directory, open oraclejetconfig.json for editing.
  2. In oraclejetconfig.json, change the paths as needed and save the file.

    For example, if you want to change the default styles path from css to app-css, edit the following line in oraclejetconfig.json:

    "styles": "app-css"
  3. Rename the directories as needed for your application, making sure to change only the paths listed in oraclejetconfig.json.
    For example, if you changed styles to app-css in oraclejetconfig.json, change the application’s css directory to app-css.
  4. Update your application files as needed to reference the changed path.

    For example, if you modified the path to the CSS for your application to app-css, update the links appropriately in your application’s index.html.

    <link rel="icon" href="app-css/images/favicon.ico" type="image/x-icon" />
    
        <!-- This is the main css file for the default Alta theme -->
        <!-- injector:theme -->
        <link rel="stylesheet" href="app-css/libs/oj/v7.2.0/alta/oj-alta-min.css" type="text/css"/>
        <!-- endinjector -->
        
        <!-- This contains icon fonts used by the starter template -->
        <link rel="stylesheet" href="app-css/demo-alta-site-min.css" type="text/css"/>
    
        <!-- This is where you would add any app specific styling -->
        <link rel="stylesheet" href="app-css/override.css" type="text/css"/>
  5. At the command prompt, from the application root directory, build your application to use the new paths.
    ojet build

Add Hybrid Mobile Features to Web Applications

Add Cordova hybrid mobile platforms to your web application using the ojet add hybrid command. When you run this command, the tooling creates a Cordova project and new src-hybrid and src-web directories, enabling you to create both web and hybrid mobile applications from the same source.

Since mobile applications typically provide a very different user experience to web applications, taking this approach allows you to add view and viewModel files that you create specifically for a mobile device user experience. Then when you build the original application by using the command ojet build hybrid, the tooling will copy your added files from the src-hybrid folder and merge them with the contents of the application's src folder. Finally, serving the application, by using the command ojet serve hybrid, populates the web staging folder with the merged source files and the tooling runs the application in the desired environment (browser, simulator, or mobile device) from this location.

Before you begin:

To add hybrid mobile platforms to your web application:

  1. At a terminal prompt, in your application’s top level directory, enter the following command to add hybrid mobile features to your web application:
    ojet add hybrid [--platforms=android,ios,windows]
                    [--appid=application-id]
                    [--appname=application-name]
                    [--help]

    You should specify at least one platform for the platforms value. Add additional platforms as needed, separated by commas. If you don’t specify a platform, the command will attempt to locate available platforms and prompt for your selection.

    --platforms=android
    --platforms=ios,android

    When you run the command, Oracle JET tooling creates the Cordova project and two new empty source directories that you can use for platform specific content: src-hybrid and src-web.

  2. To make changes to content that apply to both web and hybrid platforms, edit content in src.
  3. To make changes to content that apply only to the web or hybrid mobile platform, add the new content to src-web or src-hybrid as needed.
    When you build your application, the content in the platform specific file takes precedence over content in src. For example, if you create a new src-hybrid/js/viewModels/dashboard.html file, content in that file will take precedence over the src/js/viewModels/dashboard.html file when you build the application as a hybrid mobile application.

    Note:

    It is important that files you add to the src-web or src-hybrid folder maintain the same folder structure as the src merge target folder. For example, based on the original application's default folder structure, view or viewModel files specific to the hybrid mobile platform that you add should appear in the src-hybrid/js/view and src-hybrid/js/viewModels directories.

Build a Web Application

Use the Oracle JET command-line interface (CLI) to build a development version of your web application before serving it to a browser. This step is optional.

Change to the application’s root directory and use the ojet build command to build your application.

ojet build [--theme=themename[:android|ios|web|windows] --themes=theme1,theme2,...
            --sass]

Tip:

You can enter ojet help at a terminal prompt to get help for specific Oracle JET CLI options.
The command will take some time to complete. If it’s successful, you’ll see the following message:
Done.

The command will also create a web folder in your application’s root to contain the built content.

Note:

You can also use the ojet build command with the --release option to build a release-ready version of your application. For information, see Package and Deploy Web Applications.

About ojet build Command Options for Web Applications

Use the ojet build command with optional arguments to build a development version of your web application before serving it to a browser.

The following table describes the available options and provides examples for their use.

Option Description

theme

Theme to use for the application. The theme defaults to alta:web, but you can specify a hybrid mobile theme (alta:android, alta:ios, alta:windows) if you want your application to have the look and feel of a mobile application.

You can also enter a different themename with optional platform for a custom theme as described in Customize Themes Using the Tooling.

themes

Themes to include in the application, separated by commas.

If you don’t specify the --theme flag as described above, Oracle JET will use the first element that you specify in --themes as the default theme. .

sass

Manages Sass compilation. If you add Sass and specify the --theme or --themes option, Sass compilation occurs by default and you can use --sass=false or --no-sass to turn it off.

If you add Sass and do not specify a theme option, Sass compilation will not occur by default, and you must specify --sass=true or --sass to turn it on. For details about theming applications, see Theming an Oracle JET Application – A Typical Workflow.

Customize the Web Application’s Build Steps

Edit oraclejet-build.js to modify default build behavior. For example, you can add additional libraries to your application or change the default markers used to inject links into the application’s index.html during build time.

The Oracle JET tooling defines default build and serve behavior in node_modules/@oracle/oraclejet-tooling/lib/defaultconfig.js. The first part of the file contains the default build configuration, including entries for application paths and other options used during the build process. To modify defaults or add your own, edit oraclejet-build.js and remove comments from the options that you want to configure. The file contains detailed instructions for each configurable option.

Oracle JET will merge the options with the default configuration during the build. However, be aware that fileList options will completely replace the corresponding option in the default configuration and will not be merged.

Before you begin:

  • Familiarize yourself with the ojet build command options theme, themes, and sass, as described in Build a Web Application.
To customize build behavior:
  1. Open scripts/config/oraclejet-build.js for editing in your favorite text editor.
  2. Identify the entry that you want to change and remove the comments (//) preceding each line.

    For example, to add a custom library to the build’s staging directory, remove the comments from the copyCustomLibsToStaging entry in oraclejet-build.js as shown below:

    /**
     * # copyCustomLibsToStaging
     * This task copies any custom libraries that are not provided by JET to staging directory.
     * This task supports a single option: fileList. The fileList option defines an array of file objects. 
     * Each file object contains the following properties: 
     *   cwd, current working directory
     *   dest, destination path
     *   src, array of source file patterns
     *   rename, function to return the full path of desired destination
     * If a fileList value is specified, it completely replaces the default fileList value defined by JET
     * Example: {cwd: 'app', src: ['**', '!test.js'], dest: 'staging',  rename: function (dest, file) {return renamed path}}
     */
         copyCustomLibsToStaging: {
           fileList: [
             {
             cwd:'node_modules/oraclejet/',
             src: ['*'],
             dest: 'web/js/libs/oraclejet'
             }
           ]
         }
    
    
  3. Edit the options as desired and save the file.

    For example, to add a custom library named my_custom_module, place the module in node_modules, and edit the copyCustomLibsToStaging entry:

    copyCustomLibsToStaging: {
        fileList: [
          {
            cwd:'node_modules/my_custom_module/',
            src: ['*'],
            dest: 'web/js/libs/my_custom_module'
          }
        ]
    }
    
  4. Repeat the previous step for each option that you want to modify.
  5. Test your changes by building the web application with the desired options.
    ojet build

Serve a Web Application

Use ojet serve to run your web application in a local web server for testing and debugging. By default, the Oracle JET live reload option is enabled which lets you make changes to your application code that are immediately reflected in the browser.

Before you begin:

  • Familiarize yourself with the ojet serve command option theme when you want to run the application with an optional platform and a custom theme, as described in Customize Themes Using the Tooling.
  • Optionally, use the ojet serve command with the --release option to serve a release-ready version of your application, as described in Package and Deploy Web Applications.
To run your web application from a Command Prompt window:
  1. In a Command Prompt window, change to the application’s root directory and use the ojet serve command with optional arguments to launch the application.
    ojet serve [--server-port=server-port-number --livereload-port=live-reload-port-number
                --livereload
                --sass
                --build
                --theme=themename[:android|ios|web|windows] --themes=theme1,theme2,...
                --server-only
               ]
    
    For example, the following command will launch your application in the default web browser with live reload enabled.
    ojet serve

    Tip:

    You can enter ojet help at a terminal prompt to get help specific to the Oracle JET tooling commands and ojet serve --help to get additional help with serve options.
  2. Make any desired code change in the src folder, and the browser will update automatically to reflect the change unless you set the --no-livereload flag.

    While the application is running, the terminal window remains open, and the watch task waits for any changes to the application. For example, if you change the content in src/js/views/dashboard.html , the watch task will reflect the change in the terminal as shown below on a Windows desktop.

    Starting watcher...
    Listening on port 35729...
    Server ready: http://localhost:8000
    Watching files....
    Watcher: sass is ready...
    Watcher: sourceFiles is ready...
    Watcher: themes is ready...
    Changed: c:\web-app-navbar\src\js\views\dashboard.html
    Page reloaded resume watching...
    
  3. To terminate the process, close the application and press Ctrl+C in the command window. You may need to enter Ctrl+C a few times before the process terminates.

About ojet serve Command Options for Web Applications

Use ojet serve to run your web application in a local web server for testing and debugging.

The following table describes the available ojet serve options and provides examples for their use.

Option Description

server-port

Server port number. If not specified, defaults to 8000.

livereload-port

Live reload port number. If not specified, defaults to 35729.

livereload

Enable the live reload feature. Live reload is enabled by default (--livereload=true).

Use --livereload=false or --no-livereload to disable the live reload feature.

Disabling live reload can be helpful if you’re working in NetBeans or other IDE and want to use that IDE’s mechanism for loading updated applications.

sass

Manages Sass compilation. If you add Sass and specify the --theme or --themes option, Sass compilation occurs by default and you can use --sass=false or --no-sass to turn it off.

If you add Sass and do not specify a theme option, Sass compilation will not occur by default, and you must specify --sass=true or --sass to turn it on.

build

Build the app before you serve it. By default, an app is built before you serve it (--build=true).

Use --build=false or --no-build to suppress the build if you’ve already built the application and just want to serve it.

theme

Theme to use for the application. The theme defaults to alta:web, but you can specify a hybrid mobile theme (alta:android, alta:ios, alta:windows) if you want your application to have the look and feel of a mobile application.

themes

Themes to use for the application, separated by commas.

If you don’t specify the --theme flag as described above, Oracle JET will use the first element that you specify in --themes as the default theme. Otherwise Oracle JET will serve the application with the theme specified in --theme.

server-only

Serves the application, as if to a browser, but does not launch a browser. Use this option in cloud-based development environments so that you can attach your browser to the app served by the development machine.

Customize the Web Application’s Serve Steps

Edit oraclejet-serve.js to modify default serve behavior. For example, you can specify your own watch tasks or specify actions specific to web or hybrid applications.

The Oracle JET tooling defines default build and serve behavior in node_modules/@oracle/oraclejet-tooling/lib/defaultconfig.js. The second half of the file contains the default serve configuration, including entries for application paths and other options used during the serve process. To modify defaults or add your own, edit scripts/config/oraclejet-serve.js and remove comments from the options that you want to configure. The file contains detailed instructions for each configurable option.

Oracle JET will merge the options with the default configuration during the build. However, be aware that rewriting the three default watch targets (sourceFiles, sass, and themes) can result in unpredictable behavior.

To customize serve behavior:

  1. Open scripts/config/oraclejet-serve.js for editing in your favorite text editor.
  2. Identify the entry that you want to change and remove the comments (//) preceding each line that you want to include.

    For example, to define one or more shell commands that you want to execute after Oracle JET serves the application and you modify a source file, you can edit the sourceFiles option in the watch sub task. Remove the comments from the highlighted lines as shown below.

    // // Sub task watch default options
         watch: {
           sourceFiles:
           {
        //       files: [],
        //       options: {
        //       livereload: true
        //      },
         },
    
        //   sass: {
        //     files: [],
        //     commands: ['compileSass']
        //   },
    
        //   themes: {
        //     files: [],
        //     options: {
        //       livereload: true
        //     },
        //     commands: ['copyThemes']
        //   },
    },
    
  3. Edit the options as desired and save the file.
    For command options, add the commands option and one or more commands, each surrounded by single quotes and separated by commas. For example, the following code snippet adds node --version and npm --version to the commands option in the sourceFiles sub task:
         watch: {
           sourceFiles:
           {
        //     files: [],
        //     options: {
        //       livereload: true
        //     },
               commands: ['node --version', 'npm --version']
           },
           ... contents omitted
         },
    
  4. Test your changes by running the web application.
    ojet serve
  5. Wait for the page to reload in your browser.

    After you change one of the source files, the terminal output will display the output of the node --version and npm --version commands and reload the page.

Customize the Web Application Tooling Workflow

Hook points that Oracle JET tooling defines let you customize the behavior of the JET build and serve processes when you want to define new steps to execute during the tooling workflow using script code that you write.

When you create an application, Oracle JET tooling generates script templates in the /scripts/hooks application subfolder. To customize the Oracle JET tooling workflow you can edit the generated templates with the script code that you want the tooling to execute for specific hook points during the build and serve processes. If you do not create a custom hook point script, Oracle JET tooling ignores the script templates and follows the default workflow for the build and serve processes.

To customize the workflow for the build or serve processes, you edit the generated script template file named for a specific hook point. For example, to trigger a script at the start of the tooling's build process, you would edit the before_build.js script named for the hook point triggered before the build begins. That hook point is named before_build.

Therefore, customization of the build and serve processes that you enforce on Oracle JET tooling workflow requires that you know the following details before you can write a customization script.

  • The type of application that you created: either a web application or a hybrid mobile application.

  • The Oracle JET build or serve mode that you want to customize:

    • Debug — The default mode when you build or serve your application, which produces the source code in the built application.

    • Release — The mode when you build the application with the --release option, which produces minified and bundled code in a release-ready application.

  • The appropriate hook point to trigger the customization.

  • The location of the default hook script template to customize.

About the Script Hook Points for Web Applications

The Oracle JET hooks system defines various script trigger points, also called hook points, that allow you to customize the create, build, serve and restore workflow across the various command-line interface processes. Customization relies on script files and the script code that you want to trigger for a particular hook point.

The following table identifies the hook points and the workflow customizations they support in the Oracle JET tooling create, build, serve, and restore processes. Unless noted, hook points for the build and serve processes support both debug and release mode.

Hook Point Supported Tooling Process Description
after_app_create create This hook point triggers the script with the default name after_app_create.js immediately after the tooling concludes the create application process. A script for this hook point can be used with a web application or a hybrid mobile application.
after_app_restore restore This hook point triggers the script with the default name after_app_restore.js immediately after the tooling concludes the restore application process. A script for this hook point can be used with a web application or a hybrid mobile application.
before_build build This hook point triggers the script with the default name before_build.js immediately before the tooling initiates the build process. A script for this hook point can be used with a web application or a hybrid mobile application.
before_release_build build (release mode only) This hook point triggers the script with the default name before_release_build.js before the uglify step and the requirejs bundling step occur. A script for this hook point can be used with a web application or a hybrid mobile application.
before_hybrid_build build This hook point triggers the script with the default name before_hybrid_build.js before the cordovaPrepare and CordovaCompile build steps occur. A script for this hook point can be used only with a hybrid mobile application.
before_optimize build / serve (release mode only) This hook point triggers the script with the default name before_optimize.js before the release mode build/serve process minifies the content. A script for this hook point can be used with a web application or a hybrid mobile application.
after_build build This hook point triggers the script with the default name after_build.js immediately after the tooling concludes the build process. A script for this hook point can be used with a web application or a hybrid mobile application.
after_component_create build This hook point triggers the script with the default name after_component_create.js immediately after the tooling concludes the create Web Component process. A script for this hook point can be used to modify the build process specifically for a project that defines a Web Component.
after_component_build build (debug mode only) This hook point triggers the script with the default name after_component_build.js immediately after the tooling concludes the Web Component build process. A script for this hook point can be used to modify the build process specifically for a project that defines a Web Component.
before_serve serve This hook point triggers the script with the default name before_serve.js before the web serve process connects to and watches the application. In the case of hybrid builds, it also precedes the cordovaClean and cordovaServe step. A script for this hook point can be used with a web application or a hybrid mobile application.
after_serve serve This hook point triggers the script with the default name after_serve.js after all build process steps complete and the tooling serves the application. A script for this hook point can be used with a web application or a hybrid mobile application.

About the Process Flow of Script Hook Points

The Oracle JET hooks system defines various script trigger points, also called hook points, that allow you to customize the create, build, serve, and restore workflow across the various command-line interface processes.

The following diagram shows the script hook point flow for the create process.

The following diagram shows the script hook point flow for the build process.

The following diagram shows the script hook point flow for the serve and restore processes.

Change the Hooks Subfolder Location

When you create an application, Oracle JET tooling generates script templates in the /scripts/hooks application subfolder. Your development effort may require you to relocate hook scripts to a common location, for example to support team development.

By default, the hooks system locates the scripts in the hooks subfolder using a generated configuration file that specifies the script paths. When the tooling reaches the hook point, it executes the corresponding script which it locates using the configuration files in the /scripts/config application subfolders. If you change the default location of the hooks subfolder, you must edit the following configuration files to specify the new directory path.
  • <myApp_Home>/scripts/config/oraclejet-build.js - Specifies the location and hook type of build process scripts.

  • <myApp_Home>/scripts/config/oraclejet-serve.js - Specifies the location and hook type of serve process scripts.

If your development effort requires you to relocate hook scripts to a common location, update the path attributes in the hook system configuration files to specify the new target path for the scripts. When you edit the configuration file, do not change the type attributes. The hook system relies on the type attribute to execute the script for a specific build/serve hook point.

Create a Hook Script for Web Applications

You can create a hook point script to define a new command-line interface process step for your web application. To create a hook script, you edit the hook script template associated with a specific hook point in the tooling build and serve workflow.

The Oracle JET hooks system defines various script trigger points, also called hook points, that allow you to customize the build and serve workflow across the various build and serve modes. Customization relies on script files and the script code that you want to trigger for a particular hook point. Note that the generated script templates that you modify with your script code are named for their corresponding hook point.

To customize the workflow for the build or serve processes, you edit the generated script template file named for a specific hook point. For example, to trigger a script at the start of the tooling's build process, you would edit the before_build.js script named for the hook point triggered before the build begins. That hook point is named before_build.

A basic example illustrates a simple customization using the before_optimize hook, which allows you to control the RequireJS properties shown in bold to modify the application's bundling configuration.

requireJs.config {
  "baseUrl": "web/js",
  "name": "main-temp",
  paths: {
    "knockout":"libs/knockout/knockout-3.5.0.debug",
    "jquery":"libs/jquery/jquery-3.4.1",
    "jqueryui-amd":"libs/jquery/jqueryui-amd-1.12.1",
     ...
    "css-builder":"libs/require-css/css-builder",
    "normalize":"libs/require-css/normalize"
  }
  "optimize": "none",
  "out": "web/js/main.js"
}

A script for this hook point might add one line to the before_optimize script template, as shown below. When your build the application with this customization script file in the default location, the tooling triggers the script before calling requirejs.optimize() and changes the optimize property setting to uglify. The result is an optimized application bundle file that is also uglified.

module.exports = function (configObj) {
  return new Promise((resolve, reject) => {
    console.log("Running before_optimize hook.");
    configObj.requireJs.optimize = 'uglify';
    resolve(configObj);
  });
};

Tip:

If you want to change application path mappings, it is recommended to always edit the path_mappings.json file. An exception might be when you want application runtime path mappings to be different from the mappings used by the bundling process, then you might use a before_optimize hook script to change the requireJs.config path property.

The following example illustrates a more complex build customization using the after_build hook. This hook script adds a customize task after the build finishes.

'use strict’;

const fs = require('fs');
const archiver = require('archiver');

module.exports = function (configObj) {
  return new Promise((resolve, reject) => {
   console.log("Running after_build hook.");

    //Set up the archive
    const output = fs.createWriteStream('my-archive.war');
    const archive = archiver('zip');

    //Callbacks for the archiver
    output.on('close', () => {
      console.log('Files were successfully archived.');
      resolve();
    });
  
    archive.on('warning', (error) => {
      console.warn(error);
    });
  
    archive.on('error', (error) => {
      reject(error);
    });
  
    //Archive the web folder and close the file
    archive.pipe(output);
    archive.directory('web', false);
    archive.finalize();
  });
};

In this example, assume the script templates reside in the default folder generated when you created the application. The goal is to package the application into a ZIP file. Because packaging occurs after the application build process completes, this script is triggered for the after_build hook point. For this hook point, the modified script template after_build.js will contain the script code to zip the application, and because the .js file resides in the default location, no hooks system configuration changes are required.

Tip:

OJET tooling reports when hook points are executed in the message log for the build and serve process. You can examine the log in the console to understand the tooling workflow and determine exactly when the tooling triggers a hook point script.

Pass Arguments to a Hook Script for Web Applications

You can pass extra values to a hook script from the command-line interface when you build or serve the web application. The hook script that you create can use these values to perform some workflow action, such as creating an archive file from the contents of the web folder.

You can add the --user-options flag to the command-line interface for Oracle JET to define user input for the hook system when you build or serve the web application. The --user-options flag can be appended to the build or serve commands and takes as arguments one or more space-separated, string values:
ojet build --user-options="some string1" "some string2" "some stringx"
For example, you might write a hook script that archives a copy of the build output after the build finishes. The developer might pass the user-defined parameter archive-file set to the archive file name by using the --user-options flag on the Oracle JET command line.
ojet build web --user-options="archive-file=deploy.zip"
If the flag is appended and the appropriate input is passed, the hook script code may write a ZIP file to the /deploy directory in the root of the project. The following example illustrates this build customization using the after_build hook. The script code parses the user input for the value of the user defined archive-file flag with a promise to archive the application after the build finishes by calling the NodeJS function fs.createWriteStream(). This hook script is an example of taking user input from the command-line interface and processing it to achieve a build workflow customization.
'use strict';
const fs = require('fs');
const archiver = require('archiver');
const path = require('path');

module.exports = function (configObj) {
  return new Promise((resolve, reject) => {
    console.log("Running after_build hook.");

    //Check to see if the user set the flag 
    //In this case we're only expecting one possible user defined
    //argument so the parsing can be simple
    const options = configObj.userOptions;
    if (options){
      const userArgs = options.split('=');
      if (userArgs.length > 1 && userArgs[0] === 'archive-file'){
        const deployRoot = 'deploy';
        const outputArchive = path.join(deployRoot,userArgs[1]);

        //Ensure the output folder exists
        if (!fs.existsSync(deployRoot)) {
          fs.mkdirSync(deployRoot);
        }

        //Set up the archive
        const output = fs.createWriteStream(outputArchive);
        const archive = archiver('zip');

        //callbacks for the archiver
        output.on('close', () => {
          console.log(`Archive file ${outputArchive} successfully created.`);
          resolve();
        });

        archive.on('error', (error) => {
          console.error(`Error creating archive ${outputArchive}`);
          reject(error);
        });

        //Archive the web folder and close the file
        archive.pipe(output);
        archive.directory('web', false);
        archive.finalize();
      }
      else {
        //Unexpected input - fail with information message
        reject(`Unexpected flags in user-options: ${options}`);
      }
    }
    else {
  	//nothing to do
  	resolve();
    }
  });
};