SuiteScript2.0 - Including a custom file - javascript

Im working with suitescript 2.0 (netsuite) and Im wondering how would I go about including a custom class (object) using it's new API. For example I'm trying to include a controller class but getting a "module not found" warning. See snippet below
/**
*#NApiVersion 2.x
*#NScriptType Restlet
*/
define(['N/record', 'N/error', "src/My_Controller"],
function (record, error, My_Controller) {
var controller = new My_Controller();
...
The error message is: Module does not exist: src/My_Controller.js when in fact it is there. Is this the correct way to do it?
The NetSuite help center has nothing about inclusion of custom/ancillary javascript

You reference custom modules by their path in the File Cabinet. This can be either relative to the current file or relative to the root of the File Cabinet. So it will look something like:
define(['N/record', 'N/error', '/SuiteScripts/my-project/src/My_Controller'], ...)
or:
define(['N/record', 'N/error', './src/My_Controller'], ...)
Assuming that src is in the same directory as this file.

Related

How to make source maps available with requireJS in Tapestry 5

My goal is to use Bootstrap5 Tooltips with my Tapestry 5.8.1 web application. I try to use requireJS for my JavaScript code as much as possible. So I use the Bootstrap5 JS files in their separated form. That means, I don't use the bundle file but single files like this:
src/main/resources
- META-INF
- modules
- bootstrap5
- alert.js
- alert.js.map
- base-component.js
- base-component.js.map
- ...
- tooltip.js
- tooltip.js.map
In my own JS I activate the tooltips by defining this module:
define(["bootstrap5/tooltip"], function(Tooltip) {
var setuptooltips = function() {
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new Tooltip(tooltipTriggerEl)
})
};
return {
"setuptooltips" : setuptooltips
};
})
and then calling require(...).setuptooltips().
That all works. But.
For each *.js file in my modules/bootstrap5 directory I now get a warning on the JavaScript console about the missing source map files:
Source-Map-Fehler: Error: request failed with status 404
Ressourcen-Adresse: http://localhost:8080/webapp/modules.gz/bootstrap5/tooltip.js
Source-Map-Adresse: tooltip.js.map
And I don't know how to resolve this. Tapestry stores all the modules that are actually used in this modules.gz path. I have to knowledge of the inner workings of this. In the debugger I can browser this path and only the files that have been loaded via require() calls are listed their. Obviously, the source map files are missing. Is there a way to either resolve the issue or at least remove the warnings without the need to edit all the Bootstrap5 JS files? Since it is those JS files that refer to the source map files.
Thanks!

template node local library import

I have to setup a, most of the time, offline installation of Node-RED and need to use the "Chart.js" Library in a template node. Currently my working approach is to copy the Chart.js dictory to node-red-dashboard/dist/js and import it with <script src= "js/chart.js/dist/Chart.min.js"></script>. But when I want to update the dashboard I need to copy everything again. So it would be nice to have a permanent Solution for this.
I tryed two other approaches until now. For both I installed Chart.js to the .node-red dictory.
First I tryed it like this:
var canvas = document.getElementById('myChart').getContext('2d');
var ChartJs = require('Chart.js');
var chart = new ChartJs(canvas, {... }
in a script tag (... stands for the working chart code that is not edited), but it didn't work aswell as to put
functionGlobalContext: {chartjs:require('Chart.js')} into settings.js and change require('Chart.js') to global.get('chartjs')
Does anyone here has an Idea to solve this properly? Unfortunately the node throws no Error to the console so I don't get an idea whats wrong here.
Thanks in advance for every hint or solution,
manni
When I want to use any 3rd party charting library in my node-red dashboard, I put 2 ui_template nodes into my flow:
under "Template Type" select the "Added to site <head> section" and add the link to the library's url:
<script src="url/to/library.js"></script>
(which in your offline case would be a local url)
use the library's exported objects directly within the template, without using require, such as:
<div id="myChart"></div>
<script>
var canvas = document.getElementById('myChart').getContext('2d');
var chart = new ChartJs(canvas, { ... }
</script>
The trick is to have your local node-red instance serve the ChartJS library through a local url. For that, first add this require path line to the settings.js file, before the exports section:
// The `https` setting requires the `fs` module. Uncomment the following
// to make it available:
var fs = require("fs");
var path = require ("path");
then, uncomment the httpStatic section below that, within the exports:
// When httpAdminRoot is used to move the UI to a different root path, the
// following property can be used to identify a directory of static content
// that should be served at http://localhost:1880/.
httpStatic: path.join(__dirname, 'public'),
(you can use any directory name, in place of public) The __dirname references the node-red server's working directory, usually .node-red under your home directory.
Create this new public directory, copy the ChartJS files under it, and restart node-red. At startup, you should see a line in the console log showing the path to your new static file location:
5 Feb 12:12:23 - [info] Settings file : C:\NODE\node_red_ui\settings.js
5 Feb 12:12:23 - [info] HTTP Static : C:\NODE\node_red_ui\public
5 Feb 12:12:23 - [info] User directory : C:\NODE\node_red_ui
Now you can serve the local file public\scripts\abc.js using the local url
http://localhost:1880/scripts/abc.js
This way, npm updates to the dashboard code will not overwrite your static files.

Default "Home" text and content for JSDoc

After running a basic JSDoc compile/render from Node.js:
jsdoc file1.js file2.js
I get a well-formatted document using the default template inside a directory "out". Almost all is as expected!
But when opening the document, it always says "Home" on the index.html page, has no content on that initial page, and has "Home" in the sidebar navigation.
How and where do I notate the name of the project so that it replaces "Home"? I would also like to see a project description, as well as author and copyright information.
It seems like the most basic of things to do in a JSDoc, but I can't find the information! I have tried the following, based on some random article I found on the internet:
/**
* This JavaScript file contains foo bar baz...
*
* #projectname Project Name
* #version 0.1
* #author Greg Pettit
* #copyright 2015
*
*/
But I get no love.
[edited to add:]
Discovered the #file / #fileOverview / #overview (all synonyms) directive, which is somewhat helpful as I can now describe and set copyright/author information for each file:
/**
* #file Project description which renders below the individual filename and therefore isn't a real overview blurb.
*
* #version 0.1
* #author Greg Pettit
* #copyright 2015
*
*/
That leaves 2 "problems" to solve still:
An overview description; I think #file takes care of most of my needs, but since it's per-file, I would still like an "introduction" type paragraph or overview paragraph that appears before the descriptions of included files.
Replacing that "Home" text with custom text
Generate Home page
Create markdown file README.md
Generating jsdoc:
$ jsdoc path/to/js path/to/readme/README.md
To read more about this visit official documentation
Change 'Home' text
I don't think this is a proper way to do it but this works.
If you have jsdoc installed in your project find template file in your working directory, mine was:
./node_modules/jsdoc/templates/default/publish.js
Then search for 'Home' with search command and replace with your text, next step is to specify template when generating jsdoc:
$ jsdoc ./src/scripts/ ./README.md -t node_modules/jsdoc/templates/default/
I can't comment so I'll add a note here to clarify how to do all of the things in the original question without altering the default template, based on the directions in a file found in the "\npm\node_modules\jsdoc\templates" folder, which explains how to create your own templates. The steps to change the "Home" headings in the generated js documentation to project specific headings (e.g., "MyDescription") and include the overview blurb at the top of main page are outlined below.
Steps
First, to get the general overview onto the top of the main page of the js documentation, you would make the simple text file named README.md written in Markdown as per the answer and link above. The entire text appears at the top of the page if the path to that file is included in the command line as shown above or a reference is added in a file named conf.json, in which case you can use jsdoc -c pathTo\conf.json for the command line (see example in item 4 below). (As the link explains, you could make a file with any name or extension as long as it is in Markdown and you tell jsdoc where to find it).
Copy the folder and contents for the default template (\npm\node_modules\jsdoc\templates\default) to a new directory, renaming the new folder to something like myTemplate.
Using the advice from above for Change 'Home' text, search the file named publish.js inside the new myTemplate folder and replace "Home" with "MyDescription". Two points to note here: the file name has to remain publish.js, and "Home" appeared in two places in my original "publish.js", in the line var nav = '<h2>Home</h2>'; and the line starting generate('Home',....
Tell the jsdoc generator where to find your custom template (myTemplate folder) and your overview file ("README.md"). You can add -t pathTo\myTemplate to the command line, or you can use a very short command line, jsdoc -c pathTo\conf.json if you create a file named conf.json in a text editor, something like the file below, which specifies the source, destination, etc. for the documentation. That file puts the overview into the main page by telling the doc generator to use README.md in the "source" section, and changes the headings from "Home" to the new heading, "MyDescription", using the new myTemplate folder in the "opts" section.
{
"tags": {
"allowUnknownTags": true,
"dictionaries": ["jsdoc","closure"]
},
"opts": {
"template": "pathTo/myTemplate",
"destination": "pathTo/myJScriptDocs",
"recurse": true
},
"source": {
"includePattern": ".+\\.js(doc)?$",
"excludePattern": "(^|\\/|\\\\)_",
"include": ["pathTo/myJSSources", "pathTo/README.md"]
},
"plugins": [],
"templates": {
"cleverLinks": false,
"monospaceLinks": false
}
}
You can also add an #file (or #fileOverview) to one or more of your source files.
All of the files' overview sections will be included on the JSDoc home page. If you also feed your README to JSDoc, the file overviews will be placed after the Readme content.
Example:
/**
* #file index.js is the root file for the example.
* It kicks things off.
* #author Your name goes here
* #see DocuSign Developer Center
*/
'Home' is harcoded (passed as title when generating the index) in the default template so there is no variable or config that you could set to modify this title.
If multiple people are generating/editing the docs, editing the node_modules is an obvious no-go.
It's enough to create a layout.tmpl (or a full custom template, if you're using one), point JSDoc to it (CLI option or config file) and replace <?js= title ?> with <?js= title==='Home' ? 'Your Title' : title ?>.
I had a similar but different problem with the Home Page. The small in-house JavaScript library that I wanted to generate JSDOC pages for was just a collection of global functions, and I didn't want to display the home page at all. I only want to display the global.html page.
Since we use NPM to install JSDOC, I didn't want to duplicate the entire module just to customize the global page. Instead, I copied just the layout page to a separate directory and specified that in my jsdoc.json config file:
"templates" : {
"default": {
"layoutFile": "config/layout.tmpl"
}
}
and then I edited layout.tmpl to add a <style> tag, with a style rule that does not display the link to the home.html page:
nav > h2 {
display: none;
}

How to get current filename in dojo

How can I get the current file name I'm in, using dojo.
I have a javascript file and my break point is within that file. I want to know the file name.
and using dojo or javascipt I want to get the name of this file
Any Help will be highly appreciated
Thank you
If you are using AMD (Dojo 1.7+) you can get the module ID of the current module from the special module module:
define([ 'module' ], function (module) {
console.log(module.id);
});
If using legacy Dojo modules, the filename of the script currently being executed is never provided and cannot be retrieved in a cross-browser way because they are loaded using XHR and eval.
There is an example of that in dojo/tests/_base/loader/moduleIds.js :
function get(mid, refmod){
return require.getModuleInfo(mid, refmod, require.packs, require.modules, "../../dojo/", require.mapProgs, require.pathsMapProg, 1);
}
I tried the following in one of my modules :
require.getModuleInfo("my/Module", null, require.packs, require.modules, "../../dojo/", require.mapProgs, require.pathsMapProg, 1).url
This resolved the path to the javascript file that contains my module code...
This works too :
require.modules["my/module"].url

Is it possible to stop requireJS from adding the .js file extension automatically?

I'm using requireJS to load scripts. It has this detail in the docs:
The path that is used for a module name should not include the .js
extension, since the path mapping could be for a directory.
In my app, I map all of my script files in a config path, because they're dynamically generated at runtime (my scripts start life as things like order.js but become things like order.min.b25a571965d02d9c54871b7636ca1c5e.js (this is a hash of the file contents, for cachebusting purposes).
In some cases, require will add a second .js extension to the end of these paths. Although I generate the dynamic paths on the server side and then populate the config path, I have to then write some extra javascript code to remove the .js extension from the problematic files.
Reading the requireJS docs, I really don't understand why you'd ever want the path mapping to be used for a directory. Does this mean it's possible to somehow load an entire directory's worth of files in one call? I don't get it.
Does anybody know if it's possible to just force require to stop adding .js to file paths so I don't have to hack around it?
thanks.
UPDATE: added some code samples as requested.
This is inside my HTML file (it's a Scala project so we can't write these variables directly into a .js file):
foo.js.modules = {
order : '#Static("javascripts/order.min.js")',
reqwest : 'http://5.foo.appspot.com/js/libs/reqwest',
bean : 'http://4.foo.appspot.com/js/libs/bean.min',
detect : 'order!http://4.foo.appspot.com/js/detect/detect.js',
images : 'order!http://4.foo.appspot.com/js/detect/images.js',
basicTemplate : '#Static("javascripts/libs/basicTemplate.min.js")',
trailExpander : '#Static("javascripts/libs/trailExpander.min.js")',
fetchDiscussion : '#Static("javascripts/libs/fetchDiscussion.min.js")'
mostPopular : '#Static("javascripts/libs/mostPopular.min.js")'
};
Then inside my main.js:
requirejs.config({
paths: foo.js.modules
});
require([foo.js.modules.detect, foo.js.modules.images, "bean"],
function(detect, images, bean) {
// do stuff
});
In the example above, I have to use the string "bean" (which refers to the require path) rather than my direct object (like the others use foo.js.modules.bar) otherwise I get the extra .js appended.
Hope this makes sense.
If you don't feel like adding a dependency on noext, you can also just append a dummy query string to the path to prevent the .js extension from being appended, as in:
require.config({
paths: {
'signalr-hubs': '/signalr/hubs?noext'
}
});
This is what the noext plugin does.
requirejs' noext plugin:
Load scripts without appending ".js" extension, useful for dynamic scripts...
Documentation
check the examples folder. All the info you probably need will be inside comments or on the example code itself.
Basic usage
Put the plugins inside the baseUrl folder (usually same folder as the main.js file) or create an alias to the plugin location:
require.config({
paths : {
//create alias to plugins (not needed if plugins are on the baseUrl)
async: 'lib/require/async',
font: 'lib/require/font',
goog: 'lib/require/goog',
image: 'lib/require/image',
json: 'lib/require/json',
noext: 'lib/require/noext',
mdown: 'lib/require/mdown',
propertyParser : 'lib/require/propertyParser',
markdownConverter : 'lib/Markdown.Converter'
}
});
//use plugins as if they were at baseUrl
define([
'image!awsum.jpg',
'json!data/foo.json',
'noext!js/bar.php',
'mdown!data/lorem_ipsum.md',
'async!http://maps.google.com/maps/api/js?sensor=false',
'goog!visualization,1,packages:[corechart,geochart]',
'goog!search,1',
'font!google,families:[Tangerine,Cantarell]'
], function(awsum, foo, bar, loremIpsum){
//all dependencies are loaded (including gmaps and other google apis)
}
);
I am using requirejs server side with node.js. The noext plugin does not work for me. I suspect this is because it tries to add ?noext to a url and we have filenames instead of urls serverside.
I need to name my files .njs or .model to separate them from static .js files. Hopefully the author will update requirejs to not force automatic .js file extension conventions on the users.
Meanwhile here is a quick patch to disable this behavior.
To apply this patch (against version 2.1.15 of node_modules/requirejs/bin/r.js) :
Save in a file called disableAutoExt.diff or whatever and open a terminal
cd path/to/node_modules/
patch -p1 < path/to/disableAutoExt.diff
add disableAutoExt: true, to your requirejs.config: requirejs.config({disableAutoExt: true,});
Now we can do require(["test/index.njs", ...] ... and get back to work.
Save this patch in disableAutoExt.diff :
--- mod/node_modules/requirejs/bin/r.js 2014-09-07 20:54:07.000000000 -0400
+++ node_modules/requirejs/bin/r.js 2014-12-11 09:33:21.000000000 -0500
## -1884,6 +1884,10 ##
//Delegates to req.load. Broken out as a separate function to
//allow overriding in the optimizer.
load: function (id, url) {
+ if (config.disableAutoExt && url.match(/\..*\.js$/)) {
+ url = url.replace(/\.js$/, '');
+ }
+
req.load(context, id, url);
},
The patch simply adds the following around line 1887 to node_modules/requirejs/bin/r.js:
if (config.disableAutoExt && url.match(/\..*\.js$/)) {
url = url.replace(/\.js$/, '');
}
UPDATE: Improved patch by moving url change deeper in the code so it no longer causes a hang after calling undef on a module. Needed undef because:
To disable caching of modules when developing with node.js add this to your main app file:
requirejs.onResourceLoad = function(context, map)
{
requirejs.undef(map.name);
};

Categories