This question already has an answer here:
RequireJS: Set path to 'ignore'
(1 answer)
Closed 5 years ago.
requirejs parses JS files as text and builds a tree of all the requires...
It then injects includes into the head of an HTML file.
In a particular context I need to ignore a particular file so e.g. if it sees this it won't be added to the HTML file:
const { mixinService } = require("devtools/shared/mixinService");
I need to know how to do this because in one context I need the file but in another it will break all of my components.
Let me describe the different contexts: I work at Mozilla on the Firefox browser. Scripts can run in a privileged JS environment, where they have access to special APIs or they can run in content (like a regular webpage).
The mixinService uses some of those privileged APIs so it is incompatible with content scripts so the contexts are privileged and content. We need to ignore the require when running in the content process.
Turns out that you can use define for this so in my case it looks like this:
define("devtools/shared/mixinService", {
mixinService: {
mixins: []
}
});
require.config({
baseUrl: "resource://devtools-client-jsonview/",
paths: {
"devtools/client/shared": "resource://devtools-client-shared",
"devtools/shared": "resource://devtools/shared",
"devtools/client/shared/vendor/react":
JSONView.debug
? "resource://devtools-client-shared/vendor/react-dev"
: "resource://devtools-client-shared/vendor/react"
}
});
// Load the main panel module
requirejs(["json-viewer"]);
Easy when you know how.
Related
Tech stack - Node.js, MongoDB for the database, Strapi CMS for editing and API, React - my application.
I have a database with a long list of entries and a ready-to-use application that allows users to read data from the database. I need to be able to generate a simple website with a single entity from my database as a source to fill the template.
Mockup
Here is a mock-up. Hopefully, it will make things a bit clearer.
Clarification
After a day of thinking about the task, I believe I need something like a simplest static website generator - an application that will allow me to select a single bit of data from the list and generate a small website filled with it. The end goal is to get a website in some subfolder of my application where I can get it and use it however I need.
A bit more about specifics:
It will be used locally
Security can be neglected
Running always in development is not a problem (just in case, thinking about additional question #2)
Few additional questions:
Is it possible to run NPM scripts from the application (like npm build)
Is there any way to show one component in development mode, but replace it with another during building for production?
App.js
//...
function App() {
if() {
return <AdminUI /> // This one is to be shown in development mode
} else {
return <Website /> // This one is to be used instead of AdminUI in the build
}
UPDATE
Well, I'm digging a path to create a site generator and so far I come up with the following basic plan:
Get my template ready
Create a new directory for my website
Copy a template to the new folder
Get an HTML file, parse it to a string to modify
Swap some bits with my data
Save to a file from the modified string
repeat if needed for other files.
If that works as expected, the whole process probably might be improved by moving from a fixed template to a component, that will be prepared with a JavaScript bundler and started with the help of something like node-cmd (to run shell commands from my application)...
What you want could be achievable, but if it's just a string and little else, I'd say it's much simpler to fetch the data at startup from a given file, and populate from there. You can put a JSON file under the public folder (together with other static data, like images) and have the file being your configuration.
In the App.js file, write an async componentDidMount() and you can do an await axios.get("") with your configuration.
So App.js would look like (code written on the fly, didn't check in an IDE):
export class App extends React.App {
constructor(props) {
super(props);
this.state = { loading: true, };
}
async componentDidMount() {
const response = await axios.get("your/data.json");
this.setState({ loading: false, ... whatever})
}
render = () => (
<>
(this.state.loading && <div>Still loading...</div>)
(this.state.adminData && <AdminUI data={this.state.admingData} />)
(this.state.devData && <Website data={this.state.devData} />)
</>
)
}
If you don't care about security, wouldn't be much simpler like this? And if you use TypeScript you'll have a much much simpler life in handling the data too.
Maybe it's worth doing an AdminUI to generate the JSON, and the another UI which reads the JSON, so you end up doing two UIs. The template-generated UI could even ask for a JSON file to bootstrap directly to the user, if it simplifies... In general, an approach based on simple JSON sounds a lost simpler than going for a CI/CD pipeline.
I'm trying to run an empty simple code snippet to test SaxonJS 1.1.0 on NodeJs v8.11.1 on Windows 10.
require('./Saxon-JS-1.1.0/SaxonJS.js');
But I got this error :
PS C:\XXX\sandbox\xsl-transformation> node main.js
C:\XXX\xsl-transformation\Saxon-JS-1.1.0\SaxonJS.js:17136
setPlatform(JSTestDriver.platform);
^
ReferenceError: JSTestDriver is not defined
at initialize (C:\XXX\sandbox\xsl-transformation\Saxon-JS-1.1.0\SaxonJS.js:17136:25)
Looking at the source code, I can see :
function initialize() {
"use strict";
if (inBrowser) {
setPlatform(BrowserPlatform.platform);
saxonPrint("Saxon-JS " + getProcessorInfo().productVersion + " in browser", 0);
} else {
// Currently only Nashorn. (Later need to distinguish from Node case)
// Nashorn JSTestDriver
setPlatform(JSTestDriver.platform);
saxonPrint("Saxon-JS " + getProcessorInfo().productVersion + " in
Nashorn");
// node NodePlatform
}
if (typeof platform.initialize === "function") {
platform.initialize();
}
}
It seems Node Platform is not implemented.
However, in the documentation, it is written :
We're talking here primarily about running Saxon-JS in the browser.
However, it's also capable of running in server-side JavaScript
environments such as Node.js (not yet fully supported in this
release).
I deeply search a code snippet of SaxonJS/NodeJS but I did not find one.
Has anyone a snippet code of SaxonJS working on NodeJS ?
I'm afraid the documentation was somewhat jumping the gun. We do have users who have reported getting the code to run under Node.js, and we have done it ourselves "in the lab", but it requires source code tweaks to the issued product. As released, the code runs under two platforms, the browser platform and Nashorn (and under Nashorn, it assumes our test harness which is not released).
We're working on a version for Node.js. Doing this properly as a product needs a lot of functionality that isn't in the browser version, for example in XML parsing and serialization, debugging support, command line interfaces and APIs, etc.
Node.js Saxon-Js Instructions
This S/O question is the first listed on Google for "node.js saxon-js". So I'm answering this 4 years late because of the visibility.
[Terminal] npm install saxon-js
[IDE][xslt.js]
const saxonJs = require('saxon-js');
const fs = require('fs');
function transformDocument(source, destination, transformation, parameters) {
var xml = fs.readFileSync(source).toString()
var stylesheetParams = Object.getOwnPropertyNames(parameters)
.map(o => `QName('', '${o}') : '${parameters[o]}'`).join(",")
const html = saxonJs.XPath.evaluate(
`transform(
map {
'source-node' : parse-xml($xml),
'stylesheet-location' : $xslt,
'stylesheet-params': map {${stylesheetParams}},
'delivery-format' : 'serialized'
}
)?output`,
null,
{
params : {
'xml' : xml,
'xslt' : 'file:' + transformation
}
}
);
fs.writeFileSync(destination, html)
}
Parameters
source: xml file name
destination: output file name
transformation: xsl file name
parameters: regular json object containing any params for xslt
Characteristics
(-) extremely slow
(+) doesn't require running something on the command line every time the xslt file changes
(+) easy to use function signature based on xslt usage over the last 22 years
(+) doesn't crash
Notes
I didn't find any "Getting Started" for this. Not from Google, at least. I pieced together a working solution from multiple S/O answers.
This took me 3 hours. I hope this saves multiple developers 3 hours each.
I tried getting 'source-location' to work with a file: url, but no beans
sync I/O of course isn't necessary, it should work fine with async and nested callback functions. However, this isn't why its' slow. The xpath transform() function is quite slow, for some reason.
For some reason, this solution is stable and doesn't crash. Using Saxon-C over in Python keeps crashing, but this does not.
I'm just migrating from Magento 1.x to Magento 2.x. I found that Magento2 uses RequireJS for handling JavaScript files. So I learnt what RequireJS is, and how to use it.
I found that most of the examples uses data-main="main" to define the configuration file.
In Magento2's default_head_blocks.xml file, I found the script tag like this:
<script src="requirejs/require.js"/>
Here they did not specify any data-main.
These are my questions:
How Magento2/RequireJS knows which JS should be loaded for configuration? (I found requirejs-config.js for this in multiple places)
By default Magento2 loads lots of JS (more than 20), how can I limit them?
I could not find enough documentation on this.
The best place to get all your answers for Magento 2 JS development is the Magento 2 docs, it really is a useful resource on this. http://devdocs.magento.com/guides/v2.0/javascript-dev-guide/javascript/js_init.html explains in detail about component initialisation.
To answer your two questions above -
Q.1. How Magento2/RequireJS knows which JS should be loaded for
configuration? (I found requirejs-config.js for this in multiple
places)
In each Magento 2 module there is a requirejs-config.js file to load all that modules configuration. i.e.
var config = {
map: {
'*': {
compareItems: 'Magento_Catalog/js/compare',
compareList: 'Magento_Catalog/js/list',
relatedProducts: 'Magento_Catalog/js/related-products',
upsellProducts: 'Magento_Catalog/js/upsell-products',
productListToolbarForm: 'Magento_Catalog/js/product/list/toolbar',
catalogGallery: 'Magento_Catalog/js/gallery',
priceBox: 'Magento_Catalog/js/price-box',
priceOptionDate: 'Magento_Catalog/js/price-option-date',
priceOptionFile: 'Magento_Catalog/js/price-option-file',
priceOptions: 'Magento_Catalog/js/price-options',
priceUtils: 'Magento_Catalog/js/price-utils',
catalogAddToCart: 'Magento_Catalog/js/catalog-add-to-cart'
}
}
};
This is telling requirejs where all the required JavaScript files are located.
There are multiple way to tell Magento when to use your JS file -
data-mage-init on a HTML element. e.g. <div class="block upsell" data-mage-init="{"upsellProducts":{}}" data-limit="0" data-shuffle="0">
script tag on the page e.g
<script type="text/x-magento-init">
{
"[data-role=tocart-form], .form.map.checkout": {
"catalogAddToCart": {}
}
}
</script>
within a JS file e.g. $('.yourSelector').yourPlugin();
Q.2. By default Magento2 loads lot's of JS (more than 20), how can I
limit them?
The sheer number of JS files that are loaded as a result of multiple modules is one of the downsides, however, with the correct usage of full page caching with a reverse proxy like Varnish the performance reduction is negligible, even in a development server.
I'm using "sails": "~0.10.5" and I'm making a controller / webservice that takes get and post. Everything's fine, but I want to bring in a couple of js files I'd written earlier for processing uploaded csv's. I created a src folder on the root of my sails.js project that require a few modules, etc. I'm wondering is this the "sails.js way" of adding util / helper files?
Should I go through the extra steps of making them an npm module or is that overkill?
Yes there is :
Those file/library have to be added in api/services/ folder and be "ES6 modules"
for example create a file api/services/Hello.js
// say hello
module.exports = {
hello: function(name){
sails.log.warn("Hello was called !"); //not a good log ...
return "hello" + name + sails.config.local.helloconf; //you can then access configs and some other sails native functions;
}
};
in your controller you can then simply do something like Hello.hello("bob");
i am trying to use durandal.js for single page architecture,
i already have application where i am loading all pages in div = old approach for single page architecture,
what i want to do is when i click on page i need to open hotspa pages,
for now i write something like this . www.xyz.com#/details,
where # details is my durandal view page!
when i put <a> herf ....#/details, i got error like this :
http://postimg.org/image/hoeu1wiz5/
but when i refresh with same url, it is working fine, i am able to see view!
i do not know why i got this error
If you are using anything before version 2.0 of Durandal, you are getting this because in your Shell.js you are not defining router, or you have a bad definition of where the router module is, or possibly you are defining scripts in your index instead of 'requiring them' via require.js
1st - Check shell.js, at the top you should have a define function and it should say / do something like this, and should be exposing that to the view like so -
define(['durandal/plugins/router'], function (router) {
var shell = {
router: router
};
return shell;
};
2nd - Check and make sure the 'durandal/plugins/router' is point to the correct location in the solution explorer, in this case it is app > durandal > plugins > router. If it is not or if there is no router you can add it using nuget.
3rd - Make sure you aren't loading scripts up in your index or shell html pages. When using require.js you need to move any scripts you are loading into a require statement for everything to function properly. The 'Mismatched anonymous define() module' error usually occurs when you are loading them elsewhere - http://requirejs.org/docs/errors.html#mismatch