Vitaly Olegovitch
Vitaly Olegovitch

Reputation: 3547

Adding JavaScript files to Maven classpath using Nashorn

I would like to add some JavaScript files in the src/main/javascript folder of my Maven project. I want to be able to run them using the Nashorn JavaScript engine embedded in Java 8.

I want to run some tests that are in the src/test/javascript against the source files.

Is it possible? Is there a plugin for that?

Upvotes: 1

Views: 861

Answers (2)

A. Sundararajan
A. Sundararajan

Reputation: 4405

Nashorn has "load" builtin JS function that can load a script from:

  • File
  • URL
  • resources from classpath
  • Nashorn's bundled builtin scripts like mozilla_compat.js, FX scripts

For your specific case, you can add your .js files as resources to your application jar and invoke

load("classpath:...")

from a Nashorn script. This loads using ClassLoader.getResource, ClassLoader.getSystemResource APIs automatically.

There is a github project called "Nasven" - Nasven.js is a server, desktop, and shell-script application runtime for apps written in Javascript possibly dependent on Maven artifacts

Upvotes: 2

gclaussn
gclaussn

Reputation: 1786

You can specifiy additional resource directories by adding "build/resources/resource" tags in your pom.xml. Please have a look at following documentation:

Specifying resource directories

Another possibility is the usage of the Build-Helper-Maven-Plugin. It provides goals for adding resources and test resources. Please refer on the usage documentation.

If you have added the resource directory, you should be able to load your java script files from the classpath and execute them with the script engine Nashorn.

Upvotes: 1

Related Questions