Aurelia library js file in Bundle but is resolved as static file - aurelia

My project structure is as follows:
src
..lib
....someLibrary.js
bundles.js:
"bundles": {
"dist/app-build": {
"includes": [
"[**/*.js]",
"**/*.html!text",
"**/*.css!text"
],
"options": {
"sourceMaps": 'inline'
"inject": true,
"minify": true,
"depCache": true,
"rev": true
}
},
The project builds fine, but when I check app-build.js I don't find a definition for lib/someLibrary.js. I am using typescript for my own project so I assume this has something to do with that, how can I mix regular js files and output from my transpiled TS files into the same app-build bundle?
Update
So I tried to split the 'build-system' gulp task into two tasks: 'build-typescript' which is the same as 'build-system' was before, then I created 'build-libs' which looks like so:
gulp.task('build-libs', function() {
return gulp.src(paths.root + '**/*.js')
.pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
.pipe(changed(paths.output, {extension: '.js'}))
.pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: '/src' }).on('error', gutil.log))
.pipe(gulp.dest(paths.output));
});
I then added to my dist/app-build bundle config: "lib/someLibrary.min.js"
And now my app-build.js does have the library defined, however when I try to use the library in one of my views using:
<require from="lib/someLibrary.min.js">
I get an error:
Failed to load resource: the server responded with a status of 404 (Static File '/dist/lib/someLibrary.min.html' not found)
What?!?? Why is it looking for html when nowhere is html ever involved in this whole scenario? Why is something that should be easy this hard?
Update2
So apparently 'require' does not work with javascript files. I changed to use the 'script' tag, however it seems these get stripped out when rendered by Aurelia. I am at a loss as to how to get Aurelia to do what I want it to.

Ok so after much frustration and disbelief at how hard something so simple could be, in addition to the changes to the build tasks mentioned above (which includes the javascript library file that has no npm/jspm package into the app-bundle) I created a modified version of this solution which looks as follows:
import { bindable, bindingMode, customElement, noView } from 'aurelia-framework';
#noView()
#customElement('scriptinjector')
export class ScriptInjector {
#bindable public url;
#bindable public isLocal;
#bindable public isAsync;
#bindable({ defaultBindingMode: bindingMode.oneWay }) protected scripttag;
public attached() {
if (this.url) {
this.scripttag = document.createElement('script');
if (this.isAsync) {
this.scripttag.async = true;
}
if (this.isLocal) {
const code = 'System.import(\'' + this.url + '\').then(null, console.error.bind(console));';
this.scripttag.text = code;
} else {
this.scripttag.setAttribute('src', this.url);
}
document.body.appendChild(this.scripttag);
}
}
public detached() {
if (this.scripttag) {
this.scripttag.remove();
}
}
}
To use it, simply add the following tag to the view where you want the script library to be used as follows:
<scriptinjector url="lib/bootstrap-toc.js" is-local.bind='true'></scriptinjector>
This will keep the original scriptinjector functionality which allows you to add remote 3rd party libraries to your Aurelia app but it will also allow you to load any local 3rd party libraries that you have bundled with your app.
Hope this helps someone.

Related

VueJS, displaying static images vs. binding a function from methods [duplicate]

I'm looking for the right url to reference static assets, like images within Vue javascript.
For example, I'm creating a leaflet marker using a custom icon image, and I've tried several urls, but they all return a 404 (Not Found):
Main.vue:
var icon = L.icon({
iconUrl: './assets/img.png',
iconSize: [25, 25],
iconAnchor: [12, 12]
});
I've tried putting the images in the assets folder and the static folder with no luck. Do I have to tell vue to load those images somehow?
For anyone looking to refer images from template, You can refer images directly using '#'
Example:
<img src="#/assets/images/home.png"/>
In a Vue regular setup, /assets is not served.
The images become src="data:image/png;base64,iVBORw0K...YII=" strings, instead.
Using from within JavaScript: require()
To get the images from JS code, use require('../assets.myImage.png'). The path must be relative (see below).
So your code would be:
var icon = L.icon({
iconUrl: require('./assets/img.png'), // was iconUrl: './assets/img.png',
// iconUrl: require('#/assets/img.png'), // use # as alternative, depending on the path
// ...
});
Use relative path
For example, say you have the following folder structure:
- src
+- assets
- myImage.png
+- components
- MyComponent.vue
If you want to reference the image in MyComponent.vue, the path sould be ../assets/myImage.png
Here's a DEMO CODESANDBOX showing it in action.
A better solution would be
Adding some good practices and safity to #acdcjunior's answer, to use # instead of ./
In JavaScript
require("#/assets/images/user-img-placeholder.png")
In JSX Template
<img src="#/assets/images/user-img-placeholder.png"/>
using # points to the src directory.
using ~ points to the project root, which makes it easier to access the node_modules and other root level resources
In order for Webpack to return the correct asset paths, you need to use require('./relative/path/to/file.jpg'), which will get processed by file-loader and returns the resolved URL.
computed: {
iconUrl () {
return require('./assets/img.png')
// The path could be '../assets/img.png', etc., which depends on where your vue file is
}
}
See VueJS templates - Handling Static Assets
Right after oppening script tag just add import someImage from '../assets/someImage.png'
and use it for an icon url iconUrl: someImage
this finally worked for me, image passed as prop:
<img :src="require(`../../assets/${image}.svg`)">
What system are you using? Webpack? Vue-loader?
I'll only brainstorming here...
Because .png is not a JavaScript file, you will need to configure Webpack to use file-loader or url-loader to handle them. The project scaffolded with vue-cli has also configured this for you.
You can take a look at webpack.conf.js in order to see if it's well configured like
...
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
...
/assets is for files that are handles by webpack during bundling - for that, they have to be referenced somewhere in your javascript code.
Other assets can be put in /static, the content of this folder will be copied to /dist later as-is.
I recommend you to try to change:
iconUrl: './assets/img.png'
to
iconUrl: './dist/img.png'
You can read the official documentation here: https://vue-loader.vuejs.org/en/configurations/asset-url.html
Hope it helps to you!
It works for me by using require syntax like this:
$('.eventSlick').slick({
dots: true,
slidesToShow: 3,
slidesToScroll: 1,
autoplay: false,
autoplaySpeed: 2000,
arrows: true,
draggable: false,
prevArrow: '<button type="button" data-role="none" class="slick-prev"><img src="' + require("#/assets/img/icon/Arrow_Left.svg")+'"></button>',
Having a default structure of folders generated by Vue CLI such as src/assets you can place your image there and refer this from HTML as follows <img src="../src/assets/img/logo.png"> as well (works automatically without any changes on deployment too).
I'm using typescript with vue, but this is how I went about it
<template><div><img :src="MyImage" /></div></template>
<script lang="ts">
import { Vue } from 'vue-property-decorator';
export default class MyPage extends Vue {
MyImage = "../assets/images/myImage.png";
}
</script>
You could define the assets path depending on your environment
const dev = process.env.NODE_ENV != 'production';
const url = 'https://your-site.com';
const assets = dev ? '' : url;
<template>
<img :src="`${assets}/logo.png`"/>
<p>path: {{assets}}</p>
</template>
<script>
export default {
data: () => ({
assets
})
}
</script>
Ideally this would be inside an utils js file, or as an extended app defineProperty, like:
const app = createApp(component);
app.config.globalProperties.$assets = assets;
app.mount(element);
and will be available as:
<template>
<img :src="`${$assets}/logo.png`"/>
<p>path: {{$assets}}</p>
</template>
<script>
export default {
mounted() {
console.log(this.$assets);
}
}
</script>
load them in created, mounted or where you need them
async created() {
try {
this.icon = (await import('#assets/images/img.png')).default;
} catch (e) {
// explicitly ignored
}
and then
<img :src=icon />
Inside code you can directly require image using.
const src = require("../../assets/images/xyz.png");
Or
In order to dynamically load image need this.
const image = new window.Image();
image.src = require("../../assets/images/xyz.png");
image.onload = () => {
// do something if needed
};

How to load dynamic image from assets folder in NuxtJS

I have 2 problems:
If I use the variable in src:
I will get this link in the web and not exactly:
http://localhost:3000/~/assets/product/image/bg.png
Similar to the first problem.
I want to use dynamic css file in head() method:
export default {
head () {
const style = this.$cookie.get('app_style')
return {
link: [
{ rel: 'stylesheet', href: ~/assets/${style}.css }
]
}
}
}
To load dynamic images in the asset folder you can use require to tell webpack which image to load like so. In your template you can do:
<img :src="require(`../assets/img/${folderType}/bg1.png`)" />
Note: assuming folderType is defined in your script section
You can extract the require statement into a computed property(would make your template cleaner). So like so:
export default {
// ...
data() {
return {
folderType: 'folderTypeGoesHere'
}
},
computed: {
imagePath () {
return require(`../assets/img/${this.folderType}/bg1.png`) // the module request
}
}
}
Then in your template just use:
<img :src="imagePath" />
For your second problem, you could resolve to not using the tilde ~ alias and just use a relative path as I did in the image path example above.
It depends on your Nuxt version and also the bundler.
In Nuxt2 address starts with ~\assets\ however in Nuxt3 it starts with \assets\ .
Consider some png images in assets directory and the name of one of them is in img variable which can be changed dynamically.
If you are using Nuxt2 and Webpack, you need to use require like the following.
<img :src="require(`~/assets/${img}.png`)">
If you are using Nuxt3 and Vite
<img :src="`/assets/${img}.png`"/>

intern.js How to test legacy non modular code

I'm using intern.js as a test framework to test dojo modules and it works well.
Now I have to test some non modular legacy code but I can't.
This is an example of a simple file to test:
var Component = function() {
this.itWorks = function() {
return true;
}
};
And this is the test
define([
'intern!object',
'intern/chai!assert',
'intern/order!controls/component',
], function (registerSuite, assert) {
registerSuite({
name: 'test legacy code',
'simple test': function () {
console.log(Component);
}
});
});
The test fails sayng that "Component is not defined".
I've notice that it works only if I write
window.Component = Component
At the bottom of file to test.
I can't modify all the file to test, is it possible to test the file in a different way?
This should work fine. One possible issue is where you're loading component from. The 'controls/component' dependency in 'intern/order!controls/component' is, barring any special loader config, relative to the file doing the loading. That means that if the project is setup like this:
project/
controls/
component.js
tests/
intern.js
componentTest.js
and component is being loaded from componentTest.js, then the dependency should be 'intern/order!../controls/component.js'. (It will actually work without the '../' in this case since controls is a top level directory in the project.)
Another potential issue is that a non-AMD identifier should use the .js suffix. This tells the loader that the thing being loaded is a generic script rather than an AMD module.
Also note that the order plugin is only needed to load multiple legacy files in a specific order. If order doesn't matter, or you're just loading one script, you can just use the script itself '../controls/component.js' as the dependency.
<"/"https://stackoverflow.com/tags" term="legacy" /">
<"/!-- begin snippet: js hide: false console: true babel: false --"/">
"var Component" = function() {
"this.itWorks" = function() {
return=true;
}
};
<"/"!-- end snippet --"/">

Including dojo/dom library to Spring Roo

How is it possible to include and use the dojo/dom library in Spring roo.
This:
<script type="text/javascript">
dojo.require('dojo/dom');
dojo.ready(function remAttr(){
dojo.removeAttr('theId', 'value');
}
);
</script>
results in:
"NetworkError: 404 Introuvable - http://localhost:8131/suivitrc/resources/dojo/dom.js"
dom.js
Could not load 'dojo/dom'; last tried '../dojo/dom.js'
Can anyone please help?
I think the version of dojo in roo is currently less than 1.7. This means you can remove the following line from your code because the remoteAttr function is part of dojo.js:
dojo.require('dojo/dom');
see here: http://dojotoolkit.org/reference-guide/1.7/dojo/removeAttr.html
The namespace => to module path is retreived by replacing periods (.), in short - you need to replace the slash with a dot. Your require should be
dojo.require('dojo.dom'); // blocking call? djConfig.async must be false
Since the error is in regards to the dojo.require specified path, this means your dojo.js is found and loaded (dojo.require is not undefined) - and baseUrl is not of concern to dojo modules.
The thing is, youre using the legacy loader to pull in an AMD module, in 1.7+ the require statement has a different look to it.
// AMD loader form is
function callbackFunctionOnComplete(dojoDom) { }
require([ "dojo/dom" ], callbackFunctionOnComplete); // non-blocking
So, how dojo.require works is following, assume that the parameter we pass as string is called 'module;
dojo.require = function(module) {
var parts = module.split('.');
1 - get toplevel namespace (global)
var packageName = parts.shift(); // first part is the package name
2 - get the filename (minus .js)
var id = parts.pop(); // the last bit
3 - translate everything in between to a path (relative to packagelocation)
var mid = parts.join("/");
4 - lookup package (from toplevel) location
var fullpath = // in pseudo
foreach dojoconfig.packages
iff obj.name == packageName
set to obj.location
5 append the rest and start downloading module
fullpath += mid + id + '.js'
transport.get(..... fullpath .....)
You need to configure dojo with dojo config. I prefer the form explained here:
http://dojotoolkit.org/reference-guide/1.7/dojo/_base/config.html#explicitly-creating-a-dojoconfig-object-before-including-the-dojo-core.
And you need to tell dojo where to find its stuff. An example:
var dojoConfig =
{
baseUrl : "/yourApp/js", // defines the js folder in your webapp
tlmSiblingOfDojo: false,
async: true,
parseOnLoad:true,
packages: [
{ name: "app", location: "app"}, // where it is in the js folder
{ name: "dojo", location: "lib/dojo" }, // where it is in the js folder
{ name: "dijit", location: "lib/dijit" },
{ name: "dojox", location: "lib/dojox" }
]
};
Also the require form you are using is deprecated. See http://livedocs.dojotoolkit.org/dojo/require

Dojo - Issue loading widget cross-domain

I'm working on a project that requires that some custom Dojo widgets (i.e., widgets we have written ourselves) are loaded from another server. Despite my best efforts over several days, I cannot seem to get Dojo to load the widgets.
Dojo is loaded from the Google CDN, the widget is loaded from www.example.com, and the website is located at www.foo.com.
I cannot post the actual project files (this is a project for a company), but I have reproduced the error with smaller test files.
Test.html (on www.foo.com):
<html>
<div id="content"></div>
<script>
var djConfig = {
isDebug: true,
modulePaths: {
'com.example': 'http://example.com/some/path/com.example'
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.4.3/dojo/dojo.xd.js.uncompressed.js"></script>
<script type="text/javascript">
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.addOnLoad(function() {
dojo.require("com.example.widget.Test", false);
dojo.addOnLoad(function() {
new com.example.widget.Test().placeAt(dojo.byId('content'));
});
});
</script>
</html>
Test.xd.js (at www.example.com/some/path/com.example/widget/Test.xd.js):
dojo.provide("com.example.widget.Test");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.declare("com.example.widget.Test", [dijit._Widget, dijit._Templated], {
templateString: "<div dojoAttachPoint=\"div\">This is a test</div>",
postCreate: function() {
console.log("In postCreate");
console.log(this.div);
this.div.innerHTML += '!!!';
}
});
In Firebug, I am seeing an error after a delay of a few seconds saying that the cross-domain resource com.example.widget.Test cannot be loaded. However, in the 'Net' tab I am able to see that Test.xd.js is successfully downloaded, and I am able to set a breakpoint and see that the dojo.declare executes and completes without error.
I appreciate any help. Please let me know if there is any other information I can provide.
There is a different way for handling the module declarations in XD-loader. This is due to how the loader handles 'module-ready' event. You will most likely experience, that the dojo.addOnLoad never runs, since it 'knows' that certainly - some required modules are not declared.
Even so, they may very well be declared - and the change in 1.7+ versions of dojotoolkit seem to reckognize that fact. The reason for this, i believe, is that the mechanism for 'module-ready' is not implemented correctly in your myModule.xd.js modules.
It is basically a 'header' or 'closure' of the declaration, involving a few steps - wrapping everything in your basic module from dojo.provide and eof
Standard example boiler module file '{{modulePath}}/my/Tree.js'
dojo.provide("my.Tree");
dojo.require("dijit.Tree");
dojo.declare("my.Tree", dijit.Tree, {
// class definition
});
X-Domain example boiler module file '{{modulePath}}/my/Tree.xd.js
dojo._xdResourceLoaded(function(){
return {
depends: [
["provide", "my.Tree"],
["require", "dijit.Tree"]
],
defineResource: function(dojo) {
///////////////////////////////
/// Begin standard declaration
dojo.provide("my.Tree");
dojo.require("dijit.Tree");
dojo.declare("my.Tree", dijit.Tree, {
// class definition
});
/// End standard declaration
///////////////////////////////
}
}
})();