Vuejs dynamic require components - ecmascript-6

I have a array with data and want to require vue js components from it, some=thing like:
var d = ["a.vue","b.vue"];
for(var k in d){
let test = require('./'+d[k]);
...
}
It works fine but I get a warning in compile time because it tries to load only the './' - current root (without the d[k]). The components are loaded normal in the browser.
I also tried this but it didn't work:
var test = resolve => require(['./a.vue'], resolve);

Related

Browser not reloading after gulp completes building the SPFx solution

The following is the gulp.js content created by the Yeomen SPFx generator.
'use strict';
const build = require('#microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
build.initialize(require('gulp'));
After the gulp does a build it used to automatically refresh, but the new gulp.js generated by the generator doesn't.
Though I found many examples using browser-sync, I'm not sure which one to use.
What is the right way to automatically refresh/reload the browser once the gulp is done with it's tasks?.

Can't parse <content:encoded> from RSS

This is what RSS looks like: https://reddit.0qz.fun/r/dankmemes/top.json
My script perfectly parses "title", "description" and other items tags from the RSS. But it doesn't parse "content:encoded".
I tried this:
item.getChild("content:encoded").getText();
And this:
item.getChild("encoded").getText();
And this (found on Stackoverflow):
item.getChild("http://purl.org/rss/1.0/modules/content/","encoded").getText();
But nothing works... Could you help me?
The namespace is important for the getChild and similar methods to parse the content successfully.
Your third example is close, but you have the parameter order backwards, and you need to use the XmlService.getNamespace method, not a raw string. (The signature is getChild(string, namespace), not getChild(string, string).)
This one is tricky as the namespace should be included for some of the elements, and not for others. I am not an XML expert, so I don't know if this is expected behavior or not. The minimal example script below does find and log the text of the <content:encoded> elements using getChild, but I was only able to figure out when to include or exclude the namespace through trial and error. (If anyone has further info on why this is, please let me know in the comments.)
function logContentEncoded() {
const result = UrlFetchApp.fetch("https://reddit.0qz.fun/r/dankmemes/top.json");
const document = XmlService.parse(result.getContentText());
const root = document.getRootElement();
const namespace = XmlService.getNamespace("http://purl.org/rss/1.0/modules/content/");
const channel = root.getChild("channel"); // fails if namespace is included
const item = channel.getChild("item"); // fails if namespace is included
const encoded = item.getChild("encoded", namespace); // fails if namespace is EXCLUDED
console.log(encoded.getText());
}
Adding this library to the project: 1Mc8BthYthXx6CoIz90-JiSzSafVnT6U3t0z_W3hLTAX5ek4w0G_EIrNw
You can scrape the page. With this code, i.e., You can get the first content of <content:encoded> tags.
function getDataFromJson() {
var url = "https://reddit.0qz.fun/r/dankmemes/top.json";
var fromText = '<content:encoded>';
var toText = '</content:encoded>';
var content = UrlFetchApp.fetch(url).getContentText();
var scraped = Parser
.data(content)
.from(fromText)
.to(toText)
.build();
Logger.log(scraped);
return scraped;
}

System.IO.DirectoryNotFoundException when calling SerialDevice.FromIdAsync

I'm making a simple helper class for accessing my barcode scanner. I can do it using SerialPort constructor like:
new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
But I want my class to autodetect propper port name, so I first find the DeviceInformation:
var all = await DeviceInformation.FindAllAsync();
var foundBarcode = all.First(device => device.Name.ToLower().Contains("barcode"));
Then I try to get It like this:
var serialDevice = await SerialDevice.FromIdAsync(foundBarcode.Id);
But when I do so I get 'System.IO.DirectoryNotFoundException' in System.Private.CoreLib.dll.
How can I fix it?
PS.
I have serial communication capability in my manifest.
I found a solution, appearently
DeviceInformation.FindAllAsync();
returns items with different ids than
string selector = SerialDevice.GetDeviceSelector();
var all = await DeviceInformation.FindAllAsync(selector);
Now it works, I guess when first approach adds some USB identificator for emulated COMs.

Python + Selenium + PhantomJS render to PDF - multiple files

I am trying to addapt the code found in
Python + Selenium + PhantomJS render to PDF
so I instead of saving one web page as a pdf file, I can iterate over a list of urls and save each one with a specific name (from another list).
count = 0
while count < length:
def execute(script, args):
driver.execute('executePhantomScript', {'script': script, 'args' : args })
driver = webdriver.PhantomJS('phantomjs')
# hack while the python interface lags
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')
driver.get(urls[count])
# set page format
# inside the execution script, webpage is "this"
pageFormat = '''this.paperSize = {format: "A4", orientation: "portrait" };'''
execute(pageFormat, [])
# render current page
render = '''this.render("test.pdf")'''
execute(render, [])
count+=1
I tested modifying
render = '''this.render("test.pdf")'''
to
render = '''this.render(names[count]+".pdf")'''
so as to include the each name in the list using count but have not been successful.
Also tried:
dest = file_user[count]+".pdf"
render = '''this.render(dest)'''
execute(render, [])
But did not work either.
I greatly appreciate a suggestion for the appropriate syntax.
It must be very simple but I am a noobie.
Use string formatting:
render = 'this.render("{file_name}.pdf")'.format(file_name=names[count])

Can ES6's module loader also load assets (html/css/...)

ES6's modules are based on a flexible loader architecture (although the standard is not final, so ...).
Does this mean ES6's loader, based on system.js, can load all assets? I.e. CSS, HTML, Images, Text, .. files of any sort?
I ask because I'm starting to use WebComponents & Polymer which have their own HTML import, and implementing them with ES6, which has its own import/loader (system.js).
If you use SystemJS then you can load assets by using plugins:
// Will generate a <link> element for my/file.css
System.import('my/file.css!')
.then(() => console.log('CSS file loaded'));
Alternatively, you can use an import statement. This will make sure that the CSS file is loaded before the your script executes:
import 'my/file.css!';
Finally, you can retrieve the contents of the file using the text plugin:
import cssContent from 'my/file.css!text';
console.log('CSS file contents: ', cssContent);
Another option is to add the css as a dependency in JSPM config files. Basically adding the dependency in the specific package .json file and then running 'jspm install' which will add the override to package.js & jspm.config.js
I know you mentioned ES6 modules, but as that does not appear to support CSS natively, if you're looking for something standards-based to load resources dynamically and wish for something possibly somewhat less unpleasant than XMLHttpRequest, the new Fetch API might be used like this:
var myStylesheets = ['myStyles1.css', 'myStyles2.css'];
Promise.all(myStylesheets.map(url => fetch(url))).
then(arr => Promise.all(arr.map(url => url.text()))).
then(arr => {
var style = document.createElement('style');
style.textContent = arr.reduce(
(prev, fileContents) => prev + fileContents, ''
);
document.head.appendChild(style);
}).then(() => {
// Do whatever now
});
This is even cleaner with async functions:
var myStylesheets = ['myStyles1.css', 'myStyles2.css'];
async function loadStyles(stylesheets) {
let arr = await Promise.all(stylesheets.map(url => fetch(url)))
arr = await Promise.all(arr.map(url => url.text()))
const style = document.createElement('style')
style.textContent = arr.reduce(
(prev, fileContents) => prev + fileContents, ''
)
document.head.appendChild(style);
// Do whatever now
}
loadStyles(myStylesheets)
For other resource types, you can use the blob() method for images, and pending ES6 modules support, eval() for JavaScript, etc.
I faced that question 8 years later :D
In my option, I think is interesting we can use the import.meta.url to be able to load assets relatively in a web scenario. That makes it more similar that esmodules import way.
In addition to the Zamir answer, if the assets/styles are public and we do not have to handle their content, there is no need to use fetch or any ajax at all. Just use HTML tags: link, img, scripts ...
eg: Loading a sibling css file relatively
mywebsite.com
assets
a-component.css
a-component.js
function loadStyle(styleUrl) {
const linkEl = document.createElement("link");
linkEl.setAttribute("rel", "stylesheet");
linkEl.setAttribute("href", styleUrl);
document.head.append(linkEl);
}
function load(currentPath, relativePath) {
// [https:,,,mywebsite.com,assets,a-component.js]
const parts = currentPath.split('/');
// [https:,,,mywebsite.com,assets]
parts.pop();
// [https:,,,mywebsite.com,assets,./a-component.css]
parts.push(relativePath);
// https://mywebsite.com/assets/a-component.css
const absoluteUrl = parts.join('/').replace('/./', '/');
// css
const extension = relativePath.split('.').pop();
switch(extension) {
case 'css':
loadStyle(absoluteUrl);
break;
// others types
}
}
// usage in a-component.js
// https://mywebsite.com/assets/a-component.js
load(import.meta.url, "./a-component.css");
That did help me out in a pure JS Legacy personal project without SystemJS.