Polymer novice, how to get require statement - javascript

I'm having trouble starting with polymer. The purpose is (simple) ; an Express server that serve my index.html and the index.html that serve my polymer element.
And my first problem is : How do I use node_moduldes and the require statement inside of my polymer element. I think I found some leads, like Browserify or RequireJS, but it seems complicated. (And browserify didnt work..).
Could someone provide me a simple way to use the node_modules in this polymer element ?
I'll start with my project structure.
And the file :
public/index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="import" href="./bower_components/webcomponentsjs/webcomponents-lite.js">
<link rel="import" href="./elements/neito-photoresistor.html">
<title>Neito's Domotics</title>
</head>
<styl></style>
<body>
<neito-photoresistor></neito-photoresistor>
</body>
</html>
server/app.js
"use strict"
//require
var express = require('express'),
path = require('path');
//Conf const
const _port = 3000;
//Server
var app = express();
//Middleware
app.use(express.static(path.join(__dirname, '/..', 'public')));
//Routing
app.get('/', function (req, res){
res.sendFile('../public/index.html', {root: __dirname});
})
.listen(_port, function (){
console.log('Server listening on : '+_port);
});
and the polymer element him self (I know it is complete bullshit but still the require problem is here): public/elements/neito-resistor.html :
<!DOCTYPE html>
<link rel="import" href="./../bower_components/polymer/polymer.html">
<!-- I know I cannot use the script src="" tag to import my node_modules -->
<dom-module id="neito-photoresistor">
<template>
<style>
</style>
<span>Ambient luminosity = <span>{{lum_pct}}</span> %</span>
</template>
<script>
Polymer({
is: 'neito-photoresistor',
ready: function() {
var mcp = require('mcp3008.js'),//I know that this line cause problem
can = new mcp();
},
properties: {
lum_pct: {
type: Number,
notify: true,
reflectToAttribute: true,
observer: '_getValueLumPct'
}
},
_getValueLumPct()
{
lum_pct = can.poll(0, 1000, function(value){
console.log('Luminosite ambiante = '+(100-((value/1024)*100))+' % ('+value+')');
return 100-((value/1024)*100);
});
}
});
</script>
</dom-module>

Related

Remove 'All Files' option from HTML file input and limit to .json type when using File System Access API

I am using File System Access API to disable all files options when uploading files, and want to be accepted only .json files but it brings under All Files (*.*) As in pic:
I don't know if I'm entering wrong "application/json", maybe should be something else instead of this.
Official documentation https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API#examples
Can someone help?
My code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Open file</title>
</head>
<body>
<button onclick="getFile()">Open file</button>
<script>
const pickerOpts = {
types: [
{
accept: {
"application/json": [".json"],
},
},
],
excludeAcceptAllOption: true,
multiple: false,
};
let fileHandle;
async function getFile() {
[fileHandle] = await window.showOpenFilePicker(pickerOpts);
// run code with our fileHandle
}
console.log(fileHandle);
</script>
</body>
</html>

PHP + Laravel + Vue - Unexpected token '<' at app.js

I have a PHP+Vue project that I inherited from another programmer. I know the code should work because it's currently hosted on a server and running.
I downloaded the files to make some changes, and tried to run it locally (using Wampserver). However, when I try to access the site I get Uncaught SyntaxError: Unexpected token '<' (at app.js:1:1).
What I tried:
Looking into app.js (and app.css for that matter) in DevTools shows an HTML file (seems to be from base.blade.php) instead of javascript code. I checked every app.js file I could find on the project's folder and found actual code.
It seems like the wrong file is being served, but I don't know why or how to fix it. I don't have any experience with PHP.
Code:
app.js:
require('./bootstrap');
window.Vue = require('vue');
const files = require.context('./components', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
const app = new Vue({
el: '#app',
});
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
bootstrap.js:
window._ = require('lodash');
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
base.blade.php:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>#yield('title')</title>
<link href="{{ env('APP_ENV') == 'development' ? mix('css/app.css') : asset('css/app.css') }}" rel="stylesheet" defer>
<script src="{{ env('APP_ENV') == 'development' ? mix('js/app.js') : asset('js/app.js') }}" defer></script>
{{-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> --}}
<link href="https://fonts.googleapis.com/css?family=Roboto:200,300,400,500,600,700,800,900" rel="stylesheet">
#stack('head')
#stack('style')
</head>
<body>
<div id="app">
#yield('main')
</div>
</body>
#stack('script')
</html>

Problem with express-handlebars section helpers

I can't make the section helper work as intended. The body of login.hbs was parsed normally, but the js section was never parsed. I have tried using helpers inside res.render() and put section() straight into engine() and it didn't work either
app.js
import express from "express"
import expressHbs from "express-handlebars"
const app = express();
app.use(express.urlencoded({ extended:true }));
app.engine('hbs', expressHbs.engine({
defaultLayout: 'main.hbs',
helpers: {
section(name, options) {
if (!this._sections)
this._sections = {};
this._sections[name] = options.fn(this);
return null;
},
},
}));
app.set('view engine','hbs');
app.set('views','./view');
app.get("/", (req, res) => {
res.render("login");
})
app.listen(3000, () => console.log("listening"));
main.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
{{{body}}}
{{{_section.js}}}
</body>
</html>
login.hbs
<h1>Hello</h1>
{{#section "js"}}
<script>
console.log("hello world")
</script>
{{/section}}
Edit
I can't embed HTML either
login.hbs
<h1>Hello</h1>
{{#section "js"}}
<p>a paragraph</p>
{{/section}}
I tried to run it. The real reason why it is not rendering is because inside your main.hbs you need to have {{{_sections.js}}} inside the html body tags instead of just {{{_section.js}}} like you have it now. The script tag should run as well.
Sorry for the confusion with the previous answer.

One .mjs file that works on the browser and NodeJS using native JS Modules

Apologies if this question was answered, I tried searching but couldn't find what I'm looking for.
I want to build one .mjs file that has a library class code that I can use on both browser and Node.js. I don't want to use browsify or any 3rd party library. I want to use native JS Modules (.mjs). I'm willing to use Node 13.x so I completely replace my require statements with import and running experimental mode.
Here is an example, I want to use "node-fetch" for NodeJS and the native fetch API for the browser. So I called my variable "fetch". But I want to do an if statement so that if I'm running in the browser I can just use the native fetch, but If I'm in Node, I want to load the fetch api from node-fetch package.
fetch.mjs -shared code
//if node then do this.. else fetch will be defined in the browser
import fetch from "node-fetch"
export class AwesomeClass {
constructor(url)
{
this.url= url;
}
load () {
return fetch(this.url);
}
getAwesome() {}
}
index.mjs Node JS Client
import { AwesomeClass } from "./fetch.mjs"
const a = new AwesomeClass();
index.html browser Client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script type = 'module'>
import { AwesomeClass } from "./fetch.mjs"
const a = new AwesomeClass();
</script>
</body>
</html>
Thanks to #Heretic Monkey for introducing me to dynamic import I was able to write a single .mjs file that works on both browser and node js. Here is the code for those interested.
It actually forced me to only load the fetch when I need it.
fetch.mjs library
export class AwesomeClass {
constructor(url)
{
this.url= url;
}
load () {
return import ("node-fetch").then(nodeFetch => nodeFetch.default(this.url)).catch(e=> fetch(this.url))
}
getAwesome() {}
}
index.mjs (node.js client)
import {AwesomeClass} from './fetch.mjs'
const ac = new AwesomeClass("https://api.github.com");
(async () => {
try{
const res = await ac.load();
console.log(await res.json());
}
catch(e)
{console.error(e)}
})()
index.html (browser)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script type = 'module'>
import {AwesomeClass} from './fetch.mjs'
const ac = new AwesomeClass("https://api.github.com");
(async () => {
try{
const res = await ac.load();
console.log(await res.json());
}
catch(e)
{console.error(e)}
})()
</script>
</body>
</html>

Why am I getting this Angular-Mock error and Mocha test is not running

I'm getting the exact error as found here: (window.beforeEach || window.setup) is not a function. However the fix did not work, the author of the tutorial series here even mentioned the same fix.
Here is the Tuts+ author's fix:
Which is simply to place the angular-mock script tag after the Mochai and Chai scripts. Which I did so below:
test/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mocha Spec Runner</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="icon" href="../app/favicon.ico">
<link rel="apple-touch-icon" href="../app/assets/imgs/apple-touch-icon.png">
<link href="bower_components/mocha/mocha.css" rel="stylesheet">
</head>
<body>
<div id="mocha"></div>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/mocha/mocha.js"></script>
<script src="../bower_components/chai/chai.js"></script>
<!-- see Angular-mocks is here :( -->
<script src="../bower_components/angular-mocks/angular-mocks.js"></script>
<script>
mocha.setup('bdd');
</script>
<script src="main.spec.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
My main.spec.js file
/**
* #name Mocha Test Runner
* #desc Describes and runs our dashboard tests
*/
var assert = chai.assert;
var expect = chai.expect;
// This Test is designed to fail on purpose
describe('User Login', function() {
console.log('User Login');
describe('Login Failed', function() {
console.log('Login Failed');
if ('Incorrect login should fail', function() {
module('loginController')
inject(function($injector) {
apiFactory = $injector.get('ApiFactory');
});
expect(apiFactory).to.be.an('number');
});
});
});
My Gulp tasks
gulp.task('serve', function() {
return browserSync.init({
notify : false,
port : 3333,
server: {
baseDir: ['app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
gulp.task('serve-test', function() {
browserSync.init({
notify : false,
port : 4444,
server: {
baseDir: ['test', 'app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
In your index.html file, you include the angular-mocks.js script before the call to mocha.setup('bdd'). angular-mocks.js is implemented as an immediately-invoked function expression which attempts to use window.beforeEach. (https://github.com/angular/bower-angular-mocks/blob/master/angular-mocks.js#L2586)
However, mocha.js is not immediately invoked and has to be initialized with the mocha.setup function in order to add its magic to the runtime environment.
Try reversing the order of these script tags, so that mocha.js is included and initialized before angular-mocks.js.
<script src='bower_components/mocha/mocha.js'></script>
<script src='bower_components/chai/chai.js'></script>
<script>
mocha.setup('bdd');
</script>
<script src="bower_components/angular-mocks/angular-mocks.js"></script>

Categories