Quasar assets vs statics directories - webpack-dev-server

I am trying to understand the difference between assets and statics directories and when I should be using one or the other, especially in handling images.From the directory structure docs they seem to describe as
assets/ # dynamic assets (processed by webpack)
statics/ # pure static assets (directly copied)
Would really appreciate a simpler detailed explanation.

The docs explaining the difference for asset handling pretty straightforward:
Please note that whenever you bind “src” to a variable in your Vue scope, it must be one from the statics folder. The reason is simple: the URL is dynamic, so Webpack (which packs up assets at compile time) doesn’t know which file you’ll be referencing at runtime, so it won’t process the URL.
<template>
<div>
<q-img :src="thisImgDoesntWork" />
<q-img :src="thisImgWorks" />
<span class="thisCssImgFromAssetsWorks"></span>
</div>
</template>
<script>
export default {
data() {
return {
thisImgDoesntWork: '~assets/dummy.png',
thisImgWorks: '/statics/dummy.png'
}
}
}
</script>
<style lang="scss" scoped>
.thisCssImgFromAssetsWorks {
// ... because the URL can't change after compile time
background: url('~assets/dummy.png');
}
</style>

Related

Cant open local html file with WebView on React Native canOpenURL: failed for URL

2020-01-29 20:32:22.470194+0300 Myapp[8905:2391245]
-canOpenURL: failed for URL: "file:///private/var/containers/Bundle/Application/146EA027-7A**/Myapp.app/assets/src/assets/policy.html" - error: "This app is not allowed to query for scheme file"
I am getting this error on xCode console output on real device. On simulator, everything works fine.
Here is my simple full code:
import React, { Component } from 'react';
import { WebView } from 'react-native-webview';
const PolicyHTML = require('../assets/policy.html');
export default class PolicyScreen extends React.Component {
render() {
return (
<WebView
source={PolicyHTML}
style={{flex: 1}}
/>
);
}
}
Couldn't find much solution about that online, what am i missing ?
The solution for me was just add originWhitelist={['*']} in the <WebView> component and then iOS would load HTML correctly.
I was having the same issue, i am using webview and wanted to load my local html file in that webview, which works perfectly fine in Android but was not in IOS device. After a lot of research i ended up with the following solution.
I have placed my html file in the following path:
MyReactNativeProjectFolder>app>views>monthly>trip.html
Where monthly is my custom folder that i created myself and has a local html file called trip.html.
And in the view, lets say MyView.js, where i want to call my html file i used the following syntax:
<WebView originWhitelist={['*']} source={require('./monthly/trip.html')} ref={( webView1 ) => this.webView1 = webView1} />
MyView.js is in the follwing path:
MyReactNativeProjectFolder>app>views>MyView.js
If you are not getting any error on simulator then this shall fix your problem, otherwise try changing the html file path as I have mentioned above, that is in the views folder, and try again.
I hope this may resolve the error Unable to open URL file:///private/var/containers/Bundle/Application/146EA027-7A/Myapp.app/assets/src/assets/policy.html
I don't know is this can be considered as proper solution but here how i solved it;
I am not sure but as my thinking Xcode is not allowing some codes on html files, so I thought about that found some websites on google which converts to html files to 'clean html file' and removes the unnecessary codes. After cleaning I replaced the new clean file with old one and it worked.
Hope it helps (Especially in Privacy Policy Files).

React Intl: async loading just one specific locale data in a Universal App

I'm making a multi language universal app using React and I'm having a hard time to find out the best way to deal with locale data.
The app is going to be available in 16 languages and the amount of translated messages are quite big, so I can't load all the messages in one big json (as it is used in most react-intl examples) and I can't import those messages in the webpack generated bundle, I just need to load the user language messages on demand.
I was able to do it when the app is just running on the client side, but I also need it to be working on the server side too. I'm using express for server side rendering and webpack for bundling. Could anyone help to find out the best way to deal with this?
I've been working on something like this lately, although I don't have SSR in my project. I found that pairing dynamic import syntax with React's Suspense component seems to achieve the desired result in my case. Your milage may vary since you need SSR as well, but here's a rough overview of what I found to work for me:
// wrap this around your JSX in App.js:
<React.Suspense fallback={<SomeLoadingComponent />}>
<AsyncIntlProvider>
{/* app child components go here */}
</AsyncIntlProvider>
</React.Suspense>
// the rest is in support of this
// can be placed in another file
// simply import AsyncIntlProvider in App.js
const messagesCache = {};
const AsyncIntlProvider = ({ children }) => {
// replace with your app's locale getting logic
// if based on something like useState, should kick off re-render and load new message bundle when locale changes
const locale = getLocale();
const messages = getMessages(locale);
return (
<IntlProvider locale={locale} messages={messages}>
{children}
</IntlProvider>
);
};
function getMessages(locale) {
if (messagesCache[locale]) {
return messagesCache[locale];
}
// Suspense is based on ErrorBoundary
// throwing a promise will cause <SomeLoadingComponent /> to render until the promise resolves
throw loadMessages(locale);
}
async function loadMessages(locale) {
// dynamic import syntax tells webpack to split this module into its own chunk
const messages = await import('./path/to/${locale}.json`);
messagesCache[locale] = messages;
return messages;
}
Webpack should split each locale JSON file into its own chunk. If it doesn't, something is likely transpiling the dynamic import syntax to a different module system (require, etc) before it reaches webpack. For example: if using Typescript, tsconfig needs "module": "esnext" to preserve import() syntax. If using Babel, it may try to do module transpilation too.
The chunk output for a single locale will look something like this:
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{
/***/ "./path/to/en-US.json":
/*!*************************************!*\
!*** ./path/to/en-US.json ***!
\*************************************/
/*! exports provided: message.id, default */
/***/ (function(module) {
eval("module.exports = JSON.parse(\"{\\\"message.id\\\":\\\"Localized message text\\\"}\");//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9zcmMvbG9jYWxpemF0aW9uL2VuLVVTLmpzb24uanMiLCJzb3VyY2VzIjpbXSwibWFwcGluZ3MiOiIiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./path/to/en-US.json\n");
/***/ })
}]);
Hope this helps. Best of luck internationalizing your project! 😁

Gulp - How do I control processing order with gulp-concat

I'm trying to generate combined JavaScript and CSS resources into a single file using gulp-concat using something like this:
var concatjs = gulp
.src(['app/js/app.js','app/js/*Controller.js', 'app/js/*Service.js'])
.pipe(concat('app.js'))
.pipe(gulp.dest('build'));
I get a concatted file with this, but the order of the javascript files embedded in the combined output file is random - in this case the controllers are showing up before the initial app.js file, which causes problems when trying to load the Angular app that expects app.js before any of the related resources are loaded. Likewise for CSS resources that get combined end up in random order, and again the order is somewhat important - ie. bootstrap needs to load before the theme and any custom style sheets.
How can I set up the concatenation process so that the order remains intact?
Update
So it turns out the ordering above DOES actually work by explicitly specifying the file order in the array of file specs. So in this case the crucial thing is to list app/js/app.js first, then let the rest of the scripts where order doesn't matter in in any order.
The reason I failed to see this behavior (Duh!) is that Gulp Watch was running and the gulpfile.js update wasn't actually reflected in the output. Restarting gulp did update the script. Neophyte error...
Other Thoughts:
Still wondering though - is this the right place to specify build order? It seems you're now stuffing application logic (load order) into the build script, which doesn't feel right. Are there other approaches to address this?
For an angular application like the one in your example (and it's dependency management), I normally use this kind of syntax: gulp.src(['app\js\app.js', 'app\js\**\*.js']).
You can also use just gulp.src('app\js\**\*.js') if your app.js file is the first one in alphabetic order.
I see your point about moving the load file order into the build script: I had the same feeling till I started using gulp-inject for injecting the unminified files references in my index.html at development time and injecting the bundled, minified and versioned ones in the production index file. Using that glob ordering solution across all my development cycle made so sense to me that i don't think to it anymore.
Finally, a possible solution for this 'ordering smell' can be using browserify but to me it is just complicating the architecture for an angular application: in the end, as you said, you just need that one specific file is called before all the other ones.
For my js i use a particular structure/naming convention which helps. I split it up into directories by feature, where each 'feature' is then treated as a separate encapsulated module.
So for my projects i have,
app/js/
- app.js
- app.routes.js
- app.config.js
/core/
- core.js
- core.controllers.js
- core.services.js
/test/
- .spec.js test files for module here
/feature1/
- feature1.js
- feature1.controllers.js
/feature2/
- feature2.js
- feature2.controllers.js
...
So each directory has a file of the same name that simply has the initial module definition in it, which is all that app.js has in it for the whole app. So for feature1.js
angular.module('feature1', [])
and then subsequent files in the module retrieve the module and add things (controllers/services/factories etc) to it.
angular.module('feature1')
.controller(....)
Anyway, i'll get to the point...
As i have a predefined structure and know that a specific file has to go first for each module, i'm able to use the function below to sort everything into order before it gets processed by gulp.
This function depends on npm install file and npm install path
function getModules(src, app, ignore) {
var modules = [];
file.walkSync(src, function(dirPath, dirs, files) {
if(files.length < 1)
return;
var dir = path.basename(dirPath)
module;
if(ignore.indexOf(dir) === -1) {
module = dirPath === src ? app : dir;
files = files.sort(function(a, b) {
return path.basename(a, '.js') === module ? -1 : 1;
})
.filter(function(value) {
return value.indexOf('.') !== 0;
})
.map(function(value) {
return path.join(dirPath, value);
})
modules = modules.concat(files);
}
})
return modules;
}
It walks the directory structure passed to it, takes the files from each directory (or module) and sorts them into the correct order, ensuring that the module definition file is always first. It also ignores any directories that appear in the 'ignore' array and removes any hidden files that begin with '.'
Usage would be,
getModules(src, appName, ignoreDirs);
src is the dir you want to recurse from
appName is the name of your app.js file - so 'app'
ignoreDirs is an array of directory names you'd like to ignore
so
getModules('app/js', 'app', ['test']);
And it returns an array of all the files in your app in the correct order, which you could then use like:
gulp.task('scripts', function() {
var modules = getModules('app/js', 'app', ['test']);
return gulp.src(modules)
.pipe(concat('app.js'))
.pipe(gulp.dest('build'));
});

Load JavaScript and CSS files in folders in AngularJS

I have an AngularJS application and in the future, some developers in other teams will develop modules that will be installed as parts of it. So I defined the folder structure as below.
www/
index.html
app.js
modules/
modulesA/ -- will be copied when module A was installed
moduleA.js
moduleA.css
moduleA.partial.html
modulesB/ -- will be copied when module B was installed
moduleB.js
moduleB.css
moduleB.partial.html
Now I have a problem. When user installed module A, how to let AngularJS (and the application) load JS and CSS under its folder? Is there any library can load JS and CSS by folder so that I can put the code in index.html likes
<script src="/modules/**/*.js"></script>
<link src="/modules/**/*.css"/>
Otherwise, I have to add some placesholders in index.html and change the content when user installed a module, something like
<script src="/app.js"></script>
<!-- $$_JS_$$ -->
<link src="/app.css"/>
<!-- $$_CSS_$$ -->
AngularJS doesn't support what you want, but you could take a look at build tools such as Grunt or Gulp that let you "build" your application for you. In your case, these tools can look for CSS files and concatenate them into one single file. This way your index.html does not have to change if you ever add new modules.
GruntJS: http://gruntjs.com/
GulpJS: http://gulpjs.com/
Personally I use GulpJS, since it seems to be much faster & I found it easier to configure:
Included my configuration file below.
For example, the task "styles" will compile every css file it finds in the folders I specified, concatenate them, and drop them in the distribution folder.
Since there is an initial learning curve on how to use these tools, you can always integrate gulp or grunt at your own pace. For now you could let it build your css files & later expand it by concatenating JS as well and do various other tasks. In my opinion, its worth learning as it saves you so much time & effort.
var gulp = require("gulp");
var concat = require("gulp-concat");
var html2js = require("gulp-ng-html2js");
var sass = require("gulp-sass");
var clean = require("gulp-clean");
var streamqueue = require("streamqueue");
var ngDepOrder = require("gulp-ng-deporder");
var paths = {
"dist": "../server/staffing/static/",
"vendor": ['vendor/underscore/underscore.js',
'vendor/angular/angular.min.js',
'vendor/angular-route/angular-route.min.js',
'vendor/restangular/dist/restangular.min.js',
'vendor/angular-animate/angular-animate.min.js',
'vendor/angular-bootstrap/ui-bootstrap-0.7.0.min.js',
'vendor/angular-bootstrap/ui-bootstrap-tpls-0.7.0.min.js',
'vendor/angular-ui-router/release/angular-ui-router.min.js',
'vendor/angular-bootstrap-colorpicker/js/bootstrap-colorpicker-module.js',
'vendor/momentjs/min/moment.min.js'],
"scripts": ['app/**/*.js'],
"fonts": ['app-data/fonts/*.*'],
"templates": ['app/**/*.html'],
"styles": ['app/**/*.scss','vendor/angular-bootstrap-colorpicker/css/*.css']
}
gulp.task("watch", function () {
gulp.watch('app/**/*.js', ['scripts']);
gulp.watch('app/**/*.html', ['scripts'])
gulp.watch('app/**/*.scss', ['styles']);
})
gulp.task("default", ["clean"], function () {
gulp.start("scripts", "vendor", "styles", "fonts");
})
gulp.task("clean", function () {
return gulp.src(paths.dist, {read: false})
.pipe(clean({force: true}));
})
gulp.task("vendor", function () {
gulp.src(paths.vendor)
.pipe(concat("vendor.js"))
.pipe(gulp.dest(paths.dist + "js/"));
});
gulp.task("scripts", function () {
var stream = streamqueue({objectMode: true});
stream.queue(gulp.src(paths.scripts)
.pipe(ngDepOrder()));
stream.queue(gulp.src(paths.templates)
.pipe(html2js({moduleName: "templates"})));
return stream.done()
.pipe(concat("app.js"))
.pipe(gulp.dest(paths.dist + "js/"))
});
gulp.task("styles", function () {
gulp.src(paths.styles)
.pipe(sass())
.pipe(concat("staffing.css"))
.pipe(gulp.dest(paths.dist + "css/"))
})
gulp.task("fonts", function () {
gulp.src(paths.fonts).
pipe(gulp.dest(paths.dist + "fonts/"))
})
Check out the angular generator for Slush, it does what I think you want using gulp-bower-files and gulp-inject. You specify your app dependencies using bower, and these are collected and injected by gulp using gulp-inject, which then injects in your index.html the proper link/src/style tags that look very much like your own examples above. Modules' JS and CSS is also collected, minimized, concatenated and injected as well. It also compiles partials and injects those into $templateCache.
I have used it to automatically include dependencies from sub-folder modules/views using a project layout similar to yours.
Note that all your vendor dependencies will need to be bower packages that specify their dist files using the 'main' attribute in bower.json. Some packages do not do this properly, but it's easy to fork the package and add them yourself then point bower at your updated repo.

What's the best way to use Symfony2 to serve AngularJS partials?

I'm not sure how I should be serving partials from Symfony to Angular.
I was thinking I should set up a route in Symfony, and then have the controller output the file?
I wasn't sure however how to simply output a file from the controller (i.e. no twig stuff, not really rendering anything, etc.) And will this method cache it properly?
For example,if I want angular to download partials/button.html, should I set up a route like:
partials:
pattern: /web/partials/{partial}
defaults: { _controller: AcmeWebBundle:Partials:show, _format: html }
Then, in my controller have,
...
public function showAction() {
return file_get_contents(' ... path to file ...');
}
....
That obviously doesn't work.. I'm not sure how to output just a straight file without going through twig. Or maybe all my partials should just be twig files (just without any twig stuff in them)?
If you wanted to return the contents like that you would need to add the contents of the file to the response body.
use Symfony\Component\HttpFoundation\Response;
...
public function showAction() {
return new Response(file_get_contents(' ... path to file ...'),200);
}
...
But really you should just let your web server serve the file. What I do is put my partials in a sub folder under the web directory:
web/
partials/
img/
js/
css/
Then just call them domain.com/parials/partialFileName.html and because the file exists symfonys rewrites should ignore it by default and just serve the file.
Another method (mentioned here) is to put the files in your bundle's Resources/public folder, then run
php app/console assets:install --symlink
(where web is the actual directory web/)
This will generate symlinks in the web directory pointing to the public directories. So, if you have:
Acme/DemoBundle/Resources/public/partials/myPartial.html
it'll be available at:
http://www.mydomain.com/bundles/acmedemo/partials/myPartial.html

Resources