What kind of magic is polymer-serve doing that I don't get with a simple, static web server?
I just started with a simple "hello world" project. When I run polymer serve I'm able to browse to the page at http://localhost:8000/example.html and it works great. If I use static-server and browse to the same page, I get an error message in Chrome.
Uncaught TypeError: Failed to resolve module specifier "#polymer/lit-element". Relative references must start with either "/", "./", or "../".
Here's example.html, which was copied right out of the README.
<script src="node_modules/#webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>
<script type="module">
import { LitElement, html } from "#polymer/lit-element";
class MyElement extends LitElement {
static get properties() {
return {
mood: { type: String }
};
}
constructor() {
super();
this.mood = "happy";
}
render() {
return html`
<style>
.mood {
color: green;
}
</style>
Web Components are <span class="mood">${this.mood}</span>!
`;
}
}
customElements.define("my-element", MyElement);
</script>
<my-element mood="happy"></my-element>
Modules are imported by name instead of by path
check for instance this reference
From it
This change brings Polymer in line with standard npm practice, and
makes it easier to integrate Polymer with other tools and projects.
However, because browsers don't yet support importing modules by name,
it means you'll need a transform step to run Polymer modules natively
in the browser. The Polymer CLI and related tools are being updated to
do this transformation automatically.
running polymer build should create converted files (referenced by path)
Related
My HTML Script tag has a src, but then the div id to display the widget appears and then disappears on refresh. The DIV is still there but its not bringing in the source.
I don't know why as I get no error message in the Javascript debugger.
One weird thing is it doesn't disappear in Localhost but ONLY in Azure.
Refresh the page to re-produce the issue.
I'm using Blazor .NET Core, and the widget is at:
Site:
https://markstest1.azurewebsites.net/
Source file:
https://www.climatelevels.org/graphs/js/co2.php?theme=dark-unica&pid=2degreesinstitute
Source Code
Startup.cs (CORS added for site). One site is http.
Could that be an issue?
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddDefaultPolicy(//name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://www.climatelevels.org", "http://www.2degreesinstitute.org")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
DIV Tag with id to source file. Razor file.
<div id="co2-widget-container"></div>
_Host.cshtml file with tags
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="_framework/blazor.server.js"></script>
<script src="https://www.climatelevels.org/graphs/js/co2.php?theme=dark-unica&pid=2degreesinstitute"></script></script>
Seems to be loading now correctly. The answer was that Blazor was starting too early and canceling the javascript loads in the _Host file. It seems I had to add the tag
<script src="_framework/blazor.server.js" autostart="false"></script>
to the Blazor script file so it doesn't start too quickly and let's the startup file initiate Blazor instead. Then mutate the src URL into a Blazor.start() call after DOMContentLoaded is loaded.
<script>document.addEventListener("DOMContentLoaded", function () {
Blazor.start().then(function () {
var customScript = document.createElement('script');
customScript.setAttribute('src', '//www.website...');
document.head.appendChild(customScript);
});
});</script>
Resource link used:
https://github.com/dotnet/aspnetcore/issues/22643
https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-5.0
this might be a pretty common question but what I found on google does not help me.
I have a emberJs Project with all assets(images, etc) in
my-ember-project/public/assets/images/
everything works fine when i load the assets from homepage which is the root URL "/" or localhost:4200
for example in my homepage
I have a component with img tag which looks like this
<img src="assets/images/articles/article-1.jpg"/>
on another page with url localhost:4200**/articles/** I also load the same image with the same tag
but from what I've seen it tried to load the image from localhost:4200/articles/assets/images/articles/article-1.jpg and not from the correct path localhost:4200/assets/images/articles/article-1.jpg
adding "/" before "assets/images/" works for me if I'm trying to host my project on root folder
but when I need to host my project on subdirectory so my url (www.mydomain.com/ember-project-here/)
how do I load my assets from absolute path or relative to my settings of rootURL
adding {{rootURL}} seems to do nothing to me
It seems, {{rootURL}} does not work in hbs files (long time ago I used to think it does).
{{env 'rootURL'}} should work, where env is a helper defined like this:
import { get } from '#ember/object';
import { helper } from '#ember/component/helper';
import ENV from 'project-name/config/environment';
export default helper(function([path]) {
return get(ENV, path);
});
you can add a path helper:
import { helper } from '#ember/component/helper';
import ENV from 'project-name/config/environment';
export default helper(function([path]) {
return path.replace(/^~\//, ENV.rootURL);
});
The you can do:
<img src={{path "~/assets/images/articles/article-1.jpg"}} />
This is nice because you can also use variables:
<img src={{path this.myPath}} />
and myPath:
get myPath() {
return `~/assets/images/${this.args.iconName}.jpg`;
}
You've done a good research on this front. Yes, rootURL is the one you want to add to your project since you are deploying your application to a subfolder.
rootURL can be added to any Ember app using the config/environment.js file.
// config/environment.js
module.exports = function(environment) {
var ENV = {
// other configs...
rootURL: '/ember-project-here/',
};
}
The official guide can give you some additional info!
I have been using Traceur to develop some projects in ES6. In my HTML page, I include local Traceur sources:
<script src="traceur.js"></script>
<script src="bootstrap.js"></script>
and if I have a module in the HTML afterwards like:
<script type="module" src="foo.js"></script>
Then Traceur loads in that module, compiles it and everything works great.
I now want to programmatically add an ES6 module to the page from within another ES6 module (reasons are somewhat complicated). Here was my first attempt:
var module = document.createElement('script');
module.setAttribute('type', 'module');
module.textContent = `
console.log('Inside the module now!');
`;
document.body.appendChild(module);
Unfortunately this doesn't work as Traceur does not monitor the page for every script tag added, I guess.
How can I get Traceur to compile and execute the script? I guess I need to invoke something on either 'traceur' or '$traceurRuntime' but I haven't found a good online source of documentation for that.
You can load other modules using ES6 import statements or TraceurLoader API for dynamic dependencies.
Example from Traceur Documentation
function getLoader() {
var LoaderHooks = traceur.runtime.LoaderHooks;
var loaderHooks = new LoaderHooks(new traceur.util.ErrorReporter(), './');
return new traceur.runtime.TraceurLoader(loaderHooks);
}
getLoader().import('../src/traceur.js',
function(mod) {
console.log('DONE');
},
function(error) {
console.error(error);
}
);
Also, System.js loader seems to be supported as well
window.System = new traceur.runtime.BrowserTraceurLoader();
System.import('./Greeter.js');
Dynamic module loading is a (not-yet-standardized) feature of System:
System.import('./repl-module.js').catch(function(ex) {
console.error('Internal Error ', ex.stack || ex);
});
To make this work you need to npm test then include BrowserSystem
<script src="../bin/BrowserSystem.js"></script>
You might also like to look into https://github.com/systemjs/systemjs as it has great support for browser loading.
BTW the System object may eventually be standardize (perhaps under a different name) in the WHATWG: http://whatwg.github.io/loader/#system-loader-instance
Background
I have a piece of LESS code that needs to be compiled at runtime with Less.js -- it calculates some things via JavaScript -- so I can't use the task runner, etc.
In my index.html, I have:
<head>
...
<link rel="stylesheet/less" href="assets/less/DynamicHeight.less" />
...
<script type="text/javascript" src="lib/less/less.js"></script>
...
</head>
Problem
Less.js appears unable to find the file:
And when I try to access the file directly, I see:
Question
How can I add the configuration that will allow this less file to be downloaded? Am I still able to use web.config files with vNext, or do I need to do something with config.json instead?
Lead 1: Should I use Owin?
Thinking this might be the right path but I'm pretty unfamiliar.
I see a number of tutorials out there, such as K. Scott Allen's, which reference code such as:
public void Configuration(IAppBuilder app)
{
var options = new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider()
};
((FileExtensionContentTypeProvider)options.ContentTypeProvider).Mappings.Add(
new KeyValuePair<string, string>(".less", "text/css"));
app.UseStaticFiles(options);
}
However, it appears that in its current version, asp.net is looking for a signature of Configure(IApplicationBuilder app) instead.
The IApplicationBuilder class doesn't have a method along the lines of UseStaticFiles -- it only has a signature of IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware).
I have a feeling that this is likely the right path to solve the issue -- I just can't find out how to propertly configure the IAppliationBuilder to map the MIME extension.
Okay, I believe I figured it out.
Step 1: Add the appropriate library for static files
In ASP.NET vNext, this is Microsoft.Aspnet.StaticFiles.
In your project.json file, add the following under "dependencies":
"Microsoft.AspNet.StaticFiles": "1.0.0-beta2"
This adds the static middleware method that you can use later.
Step 2: Configure the app to use Static Files
Add the using statement at the top:
using Microsoft.AspNet.StaticFiles;
At this point, the app.UseStaticFiles method will be available, so your Configure method can look as follows:
public void Configure(IApplicationBuilder app)
{
var options = new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider()
};
((FileExtensionContentTypeProvider)options.ContentTypeProvider).Mappings.Add(
new KeyValuePair<string, string>(".less", "text/css"));
app.UseStaticFiles(options);
}
And voila! I get text when browsing to .less files, and no more error is appearing from LessJS.
In .NET Core 1.0.1, SeanKileen answer is still good. The following is a simple code rewrite:
public void Configure(IApplicationBuilder app, ...)
var contentTypeProvider = new FileExtensionContentTypeProvider();
contentTypeProvider.Mappings[".map"] = "application/javascript";
contentTypeProvider.Mappings[".less"] = "text/css";
app.UseStaticFiles(new StaticFileOptions()
{
ContentTypeProvider = contentTypeProvider
});
The above code EXTENDS the default mapping list (see the source), which already has ~370 mappings.
Avoid using the FileExtensionContentTypeProvider constructor overload that takes a dictionary (as suggested by JHo) if you want those 370 default mappings.
SeanKilleen's answer is right on, and still works ASP.NET Core RC1. My only improvement is to write the exact same code using collection initializers to make it cleaner.
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
{
{ ".less", "text/css" },
{ ".babylon", "text/json" },
// ....
})
});
I am trying to use the Async module of https://github.com/millermedeiros/requirejs-plugins to load the googlemap api. My index.html file contains the following requirejs configuration:
<script data-main="scripts/myscript" src="scripts/require.js"></script>
<script>
requirejs.config({
"baseUrl": "scripts",
"paths": {
"async": "require_plugins/async",
"gmaps": "gmaps",
"infobox":"http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox",
"jquery":"//code.jquery.com/jquery-2.1.1.min",
"jquery_mob":"//code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min"
},
waitSeconds: 15
});
All my javascript files are stored in a scripts folder (relative to index.html)
e.g. script/myscript.js and script/require.js and the async plugins are stored in a subfolder of script called require_plugins e.g. script/require_plugins/async.js
The javascript where I define the googlemap module is called gmaps.js (stored in the script folder) and looks as follows:
define("GMAP",['async!https://maps.googleapis.com/maps/api/js? &key=xxxxxx®ion=uk&libraries=places,geometry'], function () {
return window.google.maps;
});
I have obfuscated the key parameter intentionally here. According to the documentation, I should be able to use the gmaps module anywhere in other javascript files just by invoking it like so:
require(["gmaps"],function(GMAP)
{
map= new GMAP.Map("#map-div");
//and then some code to display the map
}
Unfortunately, it does not work at all. It seems that the googlemap library has not loaded at all. I use absolute URLs for jquery and that works fine but googlemap fails miserably. My question is: Is there something wrong with my requirejs config? I can't think of anything else causing this fault :(
My understanding is that the name you set in define() is what you need to use when writing the dependencies.
e.g.:
define('GMAP', ['async!<path>'], function() { return window.google.maps; });
require(['GMAP'], function(GMaps) { ... });
This is how I get GMaps to load for me. I have a secondary problem now that other libraries that depend on Maps no longer load.