I'm literally just trying to get a simple Polymer 3 app with lit-element to work. From VS Code, I have run polymer serve, and when I navigate to localhost:8081 to my index.html, I get the error in F12 tools:
Uncaught TypeError: Failed to resolve module specifier "#polymer/polymer/lib/mixins/properties-mixin.js".Relative references must start with either "/", "./", or "../".
This is extremely frustrating and I've been trying to resolve this issue for quite a while.
In HTML, I am simply including the file as expected:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Polymer 3</title>
<script type="module" src="./node_modules/#polymer/lit-element/lit-element.js"></script>
<script type="module" src="./MyApp.js"></script>
</head>
<body>
<my-app score='5'></my-app>
</body>
</html>
And in the JavaScript file for my custom element, I am doing the following:
import {LitElement, html} from './node_modules/#polymer/lit-element/lit-element.js';
class MyApp extends LitElement {
constructor() {
super();
}//end ctor
static get properties() {
return {
score: Number
}
}//end properties
//no get template needed. Use _render instead
_render({score}) {
return html`The score is ${score}`; //equivalent {{score}} or [[score]]
}//end _render window.customElements.define(MyApp.is, MyApp);
static get is() {
return 'my-app';
}//end is
}//end class
window.customElements.define(MyApp.is(), MyApp);
Any help would be greatly appreciated. I am very new to some of the Web component technology. I've used HTML5, CSS3, JavaScript, jQuery, etc. for a long time, but this new push for Web components and Polymer 3 is like a very different animal, and I'm having trouble grasping some aspects of the workflow.
Related
I am new to web development, This is just a simple code i created to test a new text editor I installed, I got this error while trying to import react because I was getting some other errors like; TypeError: Cannot read property 'createElement' of undefined
Please, how can i resolve this? is the import statement wrong?
import React, { Fragment } from 'react';
console.log("Testing");
var document;//made this declaration because I got a document undefined error
document.createElement("p"):
const p = document.createElement("p")
p.innerHTML = "This is to test the javascript";
const body = document.querySelector("body");
body.insertBefore(p,body.childNode[-1]);
<!DOCTYPE html>
<html>
<head>
<title>Testing vs code</title>
<link rel="stylesheet" type="text/css" href="styles.css"/>
</head>
<body>
<h1>Testing the vscode html preview package</h1>
<h2>Hello</h2>
<script type="module" src="js-prac.js"></script>
</body>
</html>
As per https://reactjs.org/docs/add-react-to-a-website.html, you need to add these two lines to your HTML file before importing your script:
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
I'm not sure that module loading is going to work the way you intend without using something like Create React App. You can remove the import statements and you can still reference React and ReactDOM in your script.
e.g.
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked comment number ' + this.props.commentID;
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
// Find all DOM containers, and render Like buttons into them.
document.querySelectorAll('.like_button_container')
.forEach(domContainer => {
// Read the comment ID from a data-* attribute.
const commentID = parseInt(domContainer.dataset.commentid, 10);
ReactDOM.render(
e(LikeButton, { commentID: commentID }),
domContainer
);
});
I Understand you want to create a simple application with React. I would recommend you to read this first https://kentcdodds.com/blog/how-to-react and then this one: https://reactjs.org/tutorial/tutorial.html
A react application can be created by importing script as you have started, but it is not the recommended way to build a react app.
Once you go through the above post, find a good tutorial of your choice on platforms of your choice be it blog or video based. I can name a few like udemy, frontend masters, pluralsight, and there are many more.
Take a look at ReactJS website.
You should create React app using Node package manager
npx create-react-app appName
or should link react scripts to your html
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
Also you can't redefine document object. This references your web page and you can access to element or DOM (Document Object Model) using document object.
I'm trying to understand how to use modules in javascript.
But it seems that if I import a module, then I cannot log anything to console.
Here's my code:
index.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="js/scene.js" type="module"></script>
<script src="js/main.js" type="module"></script>
</body>
</html>
scene.js:
class Scene {
constructor() {
console.log("Scene created");
}
}
export default Scene;
main.js:
import { Scene } from './js/scene.js';
var scene = new Scene();
console.log("Hello World");
The Expected Result:
Scene created
Hello World
The Result I Get:
Nothing (No Result)
What is wrong with my code and how can I properly use a module?
I see 3 mistakes
in index.html the first script tag is useless.
import is relative to script file, not html.
Scene.js export a default value not a variable named Scene.
solutions:
import Scene from './scene.js';
or
remove default in Scene.js, and import {Scene} from './scene.js';
In your scenario, I believe that line 1 of main.js is throwing an error. In your index.html file, you're suggesting that you have a folder named js with both javascript modules in it; however, in the main.js file, you're suggesting that scene.js is at path js/js/scene.js.
You probably meant import { Scene } from './scene.js';.
You should open your browser's console to view any errors.
For example, if you are using Google Chrome, becoming familiar with the Chrome Devtools will be invaluable in allowing you to resolve bugs like this one by yourself in the future.
The Chrome Devtools console will allow you to view errors in your website, which will give you an immediate answer on what is wrong. In addition, setting breakpoints will allow you to step-through each line of code and trace the flow of executed lines of code and the value of variables at each point in time.
Learn more here: https://developers.google.com/web/tools/chrome-devtools/javascript
I can't figure this out. I have a small app setup with an index.html that includes a javascript file. On the same directory as that file is another file named myJsModule.js with the following code:
export default class{
doStuff()
{
console.log("calling goStuff() from external Module");
}
}
The main javascript file that is loaded from the html then does the import in this way:
import myJsModule from "myJsModule";
// TESTING MODULES
let myNewModule = new myJsModule();
myNewModule.doStuff();
I have a local web server running using Node, so I'm accesing this index.hmtl through my localhost: http://127.0.0.1:8080.
Im getting the following error: Uncaught SyntaxError: Unexpected identifier (referring to myJsModule on my main js file). I also tried using babel to transpile this into previous javascript. I had the same problem using the "require".
Shouldn't my local server figure this out? Or am I using this wrong?
As of Chrome 61, modules are natively supported. I was able to get your example working with the following HTML and JavaScript.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Native Module</title>
</head>
<body>
<p>Hello, world!</p>
<script type="module">
import MyJsModule from './MyJsModule.js';
let myJsModule = new MyJsModule();
myJsModule.doStuff();
</script>
</body>
</html>
MyJsModule.js:
export default class MyJsModule {
doStuff() {
console.log("calling doStuff() from external Module");
}
}
I want to use ES6 for my next project and I'm using Traceur as transpiler for the purpose. I got it working the way described in the Getting Started guide. However I would like to compile all my source files into single minified file in a way they describe it on the Compiling Offline page. But I cannot get it to work with multiple source files organized in a nested directory structure.
Here's a sample project to explain the problem. It has index.html in root folder and two .js files under src.
<project-root>
/index.html
/src/one.js
/src/two.js
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="traceur.js" type="text/javascript"></script>
<script src="bootstrap.js" type="text/javascript"></script>
<script type="module" src="src/two.js"></script>
<script type="module">
import Two from 'src/two.js';
let t = new Two();
console.log(t);
</script>
<title>Title</title>
</head>
<body>
</body>
</html>
src/one.js
export default class One {
constructor() {
console.log("One constructor");
}
}
src/two.js
import One from 'src/one.js';
export default class Two extends One {
constructor () {
console.log("Two constructor");
super();
}
}
As I said, if I open index.html in browser, it will correctly work, printing the instance of Two to console.
But when I try to compile this offline, I get following error
PS D:\code\flattraceur> traceur.cmd src/two.js --out out\two.js
[Error: Error: ENOENT: no such file or directory, open 'D:\code\flattraceur\out\src\one.js'
Specified as src/one.js.
Imported by ../src/two.js.
Normalizes to src/one.js
locate resolved against base 'D:/code/flattraceur/out/'
]
As you can see, while compiling src/two.js, traceur looks for src/one.js under the output directory. I couldn't find any options on traceur that would let me customize the root of its search for referenced modules. I tried the --dir option too, but it fails too.
PS D:\code\flattraceur> traceur.cmd --dir src out
Error: At least one input file is needed
Any suggestions?
I'm getting the error across all browsers. I says "unable to process binding "component"...". I have read quite a number of articles including the requirejs site. I've checked out what can cause the error but I'm lost as to whether they apply to my code or not. To the best of my knowledge, I'm not manually loading anything using the script tag and every module is loaded with requirejs.
I created a knockout project using yoman: yo ko. After that components are added using yo ko:component [name of component]. The page loads fine when the most of the time but periodically gives the error below. The frequency seems to be increased when I use two components. I edited the new component and removed the reference to the knockout object and the error still happens though not as frequently.
The exact error is as follows:
Uncaught Error: Unable to process binding "component: function (){return f}"
Message: Mismatched anonymous define() module: function (a){function b(a){return h.raw?a:encodeURIComponent(a)}function c(a){return h.raw?a:decodeURIComponent(a)}function d(a){return b(h.json?JSON.stringify(a):String(a))}function e(a){0===a.indexOf('"')&&(a=a.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return a=decodeURIComponent(a.replace(g," ")),h.json?JSON.parse(a):a}catch(b){}}function f(b,c){var d=h.raw?b:e(b);return a.isFunction(c)?c(d):d}var g=/\+/g,h=a.cookie=function(e,g,i){if(void 0!==g&&!a.isFunction(g)){if(i=a.extend({},h.defaults,i),"number"==typeof i.expires){var j=i.expires,k=i.expires=new Date;k.setTime(+k+864e5*j)}return document.cookie=[b(e),"=",d(g),i.expires?"; expires="+i.expires.toUTCString():"",i.path?"; path="+i.path:"",i.domain?"; domain="+i.domain:"",i.secure?"; secure":""].join("")}for(var l=e?void 0:{},m=document.cookie?document.cookie.split("; "):[],n=0,o=m.length;o>n;n++){var p=m[n].split("="),q=c(p.shift()),r=p.join("=");if(e&&e===q){l=f(r,g);break}e||void 0===(r=f(r))||(l[q]=r)}return l};h.defaults={},a.removeCookie=function(b,c){return void 0===a.cookie(b)?!1:(a.cookie(b,"",a.extend({},c,{expires:-1})),!a.cookie(b))}}
http://requirejs.org/docs/errors.html#mismatch
Below are some of the code in the files (if it helps)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>ko-cai</title>
<!-- build:css -->
<link href="bower_modules/semantic/dist/semantic.css" rel="stylesheet">
<link href="bower_modules/c3/c3.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
<!-- endbuild -->
<!-- build:js -->
<script src="app/require.config.js"></script>
<script data-main="app/startup" src="bower_modules/requirejs/require.js"></script>
<!-- endbuild -->
</head>
<body>
<div>
<!--<side-bar></side-bar>
<page-container></page-container>-->
<dashboard></dashboard>
this is a test
</div>
</body>
</html>
require.config.js
// require.js looks for the following global when initializing
var require = {
baseUrl: ".",
paths: {
"crossroads": "bower_modules/crossroads/dist/crossroads.min",
"hasher": "bower_modules/hasher/dist/js/hasher.min",
"jquery": "bower_modules/jquery/dist/jquery",
"knockout": "bower_modules/knockout/dist/knockout",
"knockout-projections": "bower_modules/knockout-projections/dist/knockout-projections",
"signals": "bower_modules/js-signals/dist/signals.min",
"text": "bower_modules/requirejs-text/text",
"semantic": "bower_modules/semantic/dist/semantic",
"lodash": "bower_modules/lodash/dist/lodash",
"c3": "bower_modules/c3/c3",
"d3": "bower_modules/d3/d3",
"config": "../../cai/config",
"observations": "../../cai/observations"
},
shim: {
"semantic": { deps: ["jquery"] },
"c3": { deps: ["d3"]},
"config": { deps: ["knockout"]},
"observations": { deps: ["knockout","jquery"]}
}
};
dashboard.html
<h2>dashboard</h2>
<p data-bind='text: message'></p>
dashboard.ts
/// <amd-dependency path="text!./dashboard.html" />
import ko = require("knockout");
export var template: string = require("text!./dashboard.html");
export class viewModel {
public message = ko.observable("Hello from the dashboard component too!");
constructor (params: any) {
}
public dispose() {
// This runs when the component is torn down. Put here any logic necessary to clean up,
// for example cancelling setTimeouts or disposing Knockout subscriptions/computeds.
}
}
dashboard.js
define(["require", "exports", "knockout", "text!./dashboard.html"], function(require, exports, ko) {
exports.template = require("text!./dashboard.html");
var viewModel = (function () {
function viewModel(params) {
this.message = ko.observable("Hello from the dashboard component too!");
}
viewModel.prototype.dispose = function () {
// This runs when the component is torn down. Put here any logic necessary to clean up,
// for example cancelling setTimeouts or disposing Knockout subscriptions/computeds.
};
return viewModel;
})();
exports.viewModel = viewModel;
});
//# sourceMappingURL=dashboard.js.map
What am I doing wrong?
How do I fix this as it makes testing very difficult?
Where can I check which of the known issues apply to my code so I look for a fix.
After some more investigations, I was able to come up with a solution. May not be the best but I'm yet to see another. The problem had to do with require.js. It appears that it does not matter what is contained in the file (I even tried one with a blank function and got the mismatch error). I however noted that, when I execute the same require statement after the error, it actually works. I added a component loader to knockout to fetch the Config of the components. Below is the loader that worked for me. Hope it is useful to someone until a better solution is found or we get to the bottom of this issue.
//register a custom loader
ko.components.loaders.unshift({
getConfig: function(name,callback){
ko.components.defaultLoader.getConfig(name, function(c){
if (c && c.require){ //do custom loading here. make first attempt to fetch the config
try{
require([c.require],function(config){
callback(config);
});
}catch(e){
//todo: check that this is mismatch error and try again. else throw exception
require([c.require], function(config){ //make the request again
callback(config);
});
}
} else {
callback(c);
}
})
}
});
Have you checked the requirejs documentation? More precisely the list behind a link from the error you posted:
To avoid the error:
Be sure to load all scripts that call define() via the RequireJS API.
Do not manually code script tags in HTML to load scripts that have
define() calls in them.
If you manually code an HTML script tag, be sure it only includes
named modules, and that an anonymous module that will have the same
name as one of the modules in that file is not loaded.
If the problem is the use of loader plugins or anonymous modules but
the RequireJS optimizer is not used for file bundling, use the
RequireJS optimizer.
If the problem is the var define lint approach, use /*global define
*/ (no space before "global") comment style instead.
http://requirejs.org/docs/errors.html#mismatch