Svelte and Rollup: How to export components which can be fetched via AJAX, cached, and reused on multiple pages? - rollupjs

In my Svelte + Rollup project src folder I have two subfolders, components and pages. Let me describe my dream, and hopefully somebody can shed some light on whether it's possible.
The components and pages are exported as their own files (I have that working via rollup-plugin-multi-input).
When a page is hit, it requests all the components it needs.
The component JS files are then cached. All future page calls that need the same components draw from the cache.
Is this reasonable, or would it be better to just export the pages individually and bundle the components into each page, duplicating code?
Another potential idea
Do an App.svelte file that imports all the components, aggregate those into an object, pass that object into the page component as a prop, then do <svelte:component this={components.Input}> for all components inside the page.
App.svelte:
<script>
import { onMount } from 'svelte';
import Input from 'Input.svelte';
import Popup from 'Popup.svelte';
const components = {Input, Popup};
let page;
function getPage(url) {
/* AJAX call to fetch the page component and set it to the page variable */
}
onMount(() => getPage(location.pathname))
</script>
<svelte:component this={page} components>
Page1.svelte:
<script>
export let components;
</script>
<p>Type your name:</p>
<svelte:component this={components.Input}>
With this method, all the components are included in the bundle even if the user never hits a page that contains some of those.

It appears that you are talking about some sort of elaborate, manual code-splitting.
When you build a Svelte/Sapper project with Rollup, it will bundle and chunk your components, routes, etc, into a series of smaller chunks of JS, which are loaded only when required, saving bandwidth and increasing speed. You don't need the multi-input plugin for this.
Also note that your plan of loading components via AJAX won't work, since Svelte is a compiled language, and won't build and assign things on the fly in a user's browser.
Out of curiosity, what is the bundle size you are struggling with? Svelte already makes some of the tiniest bundles of any frontend framework, so what are you doing to give you size concerns?

Related

Stuck trying to hydrate ReactJS.net SSR components in raw HTML from Umbraco

I have an Umbraco CMS loosely working with ReactJS.net. I've got a root <App> component which takes an array prop of (Umbraco Node ID and Path) objects, used to generated a <Route> for each page in the site using a <Content> comp. <App> is rendered in an UmbracoViewPage and renders fine in a client browser - with #Html.ReactInitJavaScript(), it gets hydrated as expected.
The <Content> component loads up the page HTML using dangerouslySetInnerHTML. I've got a few custom Umbraco grid editors which, instead of generating conventional markup in the ASP .NET view, instead call #Html.React() to render a custom React component which might take a prop or two.
On initial page load, the grid HTML is generated server-side and these nested components work fine in the browser, because ReactJS.net is passing ReactDOM.hydrate() calls for each grid component (triggered by #Html.ReactInitJavaScript()).
BUT as soon as there is a frontend route change, the <App> mounts the relevant <Content> comp based on the path and this calls an Umbraco SurfaceController with the Umbraco Node ID. The page grid HTML for that node is returned and loaded as before using dangerouslySetInnerHTML.
The problem is I now have raw HTML which includes multiple React components which need hydrating. Because it's loading in the browser, there is no longer a #Html.ReactInitJavaScript() call hydrating all the components individually.
How can I achieve this?
Note: Answering my own question in case it helps anyone who is playing with Umbraco and React and is aiming for a tighter integration.
TL;DR - Include a list of component names, React IDs and props in my content API responses, allowing my frontend code to handle it much the same as ReactJS.NET's #Html.ReactInitJavaScript helper does (I think).
My solution was to modify my SurfaceController to include a list all of the React components rendered in the markup. So it does much the same as ReactJS.NET's #Html.ReactInitJavaScript helper but in my SurfaceController API method.
I extended ReactJS.NET's #Html.React helper so that details about the component called are also added to a custom helper service I named ReactComponentHydrator (gist, per-request singleton)*. For each component, I store the component name (e.g. Component.ExampleComponent), the React ID included in the HTML markup (e.g. react_d1gC4eKqaUatZWfAdtjkTA) and the props sent with it.
From that, in the frontend code I am to create and hydrate each component once the HTML has been loaded via dangerouslySetInnerHTML.
*ReactJS.NET does seem to keep track of each component called but this is internal and not exposed through any API I could find.

How to keep related Partial page/HtmlHelpers, scripts and css together and not separate references

I have a form that has a button next to person textbox that brings up a person Bootstrap Modal Search Window.
the html I put in a partial page and reference it
#{await Html.RenderPartialAsync("_PersonControlPartialHtml","PersonControl1");}
#{await Html.RenderPartialAsync("_PersonControlPartialHtml","PersonControl2");}
which adds a textbox and button.
Then I add a bootstrap modal html to the page that only has to appear once per page
#{await Html.RenderPartialAsync("_PersonControlModal");}
Then the javascript event code and css for the above.
#section Header {
<script src="~/css/personcontrolscript.css"></script>
}
and
#section Scripts {
<script src="~/js/personcontrolscript.js"></script>
}
The html I could put in an htmlhelper but I still need to add 3 references to the page if I want to add it to a page.
Is there not an easier way?
There are ways to reduce this but those ways come with trade offs. So it really depends on which approach best fits your needs.
So for example you could eliminate adding the .css reference in the header section via two different approaches:
1) you could place those styles in a global.css file that is already loaded for ever page; or
2) you could use inline styles on you html and eliminate these css classes.
Both of these solutions of course have downsides. Approach one means that the size of the global.css styles will be larger and take a bit more time to load even if the first page used on the site doesn't need them. Approach 2 seems to fly in the face of conventional wisdom that you should almost never use inline styles and it will make the markup more verbose. But either solution would allow you to eliminate the need for including a seperate ~/css/personcontrolscript.css reference every time you have a person control on the page.
As for the need to include ~/js/personcontrolscript.js, that could be solved one of two ways:
1) include the javascript code in a global.js file that is loaded for every page; or
2) put that javascript code inline in the _PersonControlPartialHtml and add code to it to make sure that it only gets injected the first time the partial is used on the page.
As for the bootstrapModel, I'm a little less clear on what that code looks like so I can't say for sure but probably it could leverage an approach similar to one mentioned for css or js.
With regard to rendering your partials, I don't think there is any way to eliminate that given that it's the primary representation of the functionality you are adding to the page.

Angularjs Light version

I use angular in many projects, specially in ASP.NET MVC, but i dont like angular-
router (also ui-router, this is not much problem indeed as it's just a plugin) - concept of web-apps kills all ASP.NET features
services and factories - as all of this can be done inside common controller. (This might sound tricky)
constants and values - as i dont think this is really needed if you use requirejs or other AMD
What i love in angular is just directives, and when i make big nested directive, i use same controller foreach, so there is no $scope interacting (less watchers)
.controller('BaseGridCtrl', function(){
//instead of
//$scope.value = 123;
var ctrl = this;
//this is for Table-base-directive
ctrl.value = 123;
//this is for Table-head-directive
ctrl.value2 = 123;
});
.directive('table-base', function(){
return {
template: '<div>{{bgc.value}}</div>',
controller: 'BaseGridCtrl',
controllerAs: 'bgc'
}
});
.directive('table-head', function(){
return {
template: '<div>{{bgc.value2}}</div>',
controller: 'BaseGridCtrl',
controllerAs: 'bgc'
}
});
.directive('table-foot', function(){
return {
template: '<div>{{bgc.value3}}</div>',
controllerAs: 'bgc',
controller: function(){
var ctrl = this;
ctrl.value3 = 123;
}
}
});
So the link function is used veeery rare. And specially i like that angular easily detects directive - which is great as you just write 1 tag <grid> instead of reactjs components (This also might sound tricky). In my projects i use DotLiquid for razor views (it's stored in database as string) Sample:
<grid theme="some" route="localhost:9000/some/action"></grid>
So dotLiquid just renders this string w/o problem, or even applies other bingings beside angularjs. And this is great as all stuff is self contained. Which cannot be achieved by reactjs - you need to bootstrap components by yourself
React.renderComponent(<Grid />, document.querySelector('#someId'))
resume
Currently it's heavy, about 100kb, but without all this unnecessary stuff it would be really light. I would like to use only directive and controller services, Also with server-side rendering angular gonna bootstrap itself on each request which is not wise, but with lighter version it's a bit tradeoff.
Has anybody tried to strip angular services succesfully? Or is there any consideration, any ideas?
edit
Angular-light looks promising, but:
it doesn't provide HTML tag detection, only attributes
really ugly, alight.directives.al.getValue this looks so bad only for me or someone else?
edit2
Ok, that 100kb might not play alot. But consider it as workout, as you might know, angular start only once, at page load, so it must build the app, pull all modules, configure each, then all services of module, then inject them where they are needed, then supply callbacks from factories and services to any who injects them, at least it gonna check if any exists (on each module), all of this happens at start, only once! By wiping up size, we also can minimize javascript execution(indeed it will), factory and service watchers, so we won't need any parts that aren't used. We can even get rid of controllers (and use them inline), only 1 service. angular.directive (which is best part of party). Have looked at mustache, handlebars, but they are just like reactjs.
You can try Angular Light ~15kb (gzipped), it doesn't have services, factories, constants, values, DI, router and so on.
In addition, it has helpful features like text-directives and a support of Object.observe (benchmark)
edit
It provides HTML tag detection, attributes and comments.
AngularJS is meant for full SPA development. This means that you are not making full round trips to the server all the time. If your application needs to pass data back and forth, utilize the WEB API controllers and pass JSON up to them.
An Asset Management System I am currently working on is full SPA with WEB API and MVC fully wrapped into its needs. User log-in is processed across a full page request everything else is SPA. Additionally, here is something to read more about using MVC/WebAPI and Angular together.
If you are trying to use AngularJS instead of something like BackboneJS then you should be using AngularJS Light which was started for this exact purpose. I haven't used this library specifically, but as it is suppose to be an alternative to libraries I do use. The suggestion, if you want Angular and not BackboneJS or KnockoutJS use AngularJS Light

How to separate javascript libraries and calls in the Rails 3.1 asset pipeline

I'm trying to get the hang of the whole asset pipeline thing, and read the guide and several tutorials about them. But one thing that doesn't become quite clear is wether I should view my javascript asset files as a library or a place to put code that is actually run i.e. $(document).ready. Because by default all the javascript files are included, and it would be weird to have several $(document).ready's in there, not to mention that you don't want the $(document).ready function for every page to be run in the first place. What would be the way to go at this? Use my asset files as a library and put actual calls in my views (ugly)? Or is there a better way to do this?
I too ran into this issue. In a large project you can have somebody put code into document ready to, for example, add a click function to each li within a div with class container.
Now we could all argue that the above code would be too generic and of course may affect li tags in other parts of the application, but the bigger the project, the more likely it is that you will run into a conflict like this leading to unexpected behaviour.
I for one am uncomfortable with a whole bunch of document ready functions running for each and every page loaded. My solution is not necessarily the perfect one, but it's one that I have taken up and will share with you.
In the body tag of each page I add data elements signifying the controller and the action. I then have one document ready script that looks for a class named after the controller with the name Ready appended e.g. HomeReady. It will then call a method on this class (presuming it exists) named after the action. So in your asset coffee file you could write:
class #HomeReady
#index: ->
alert("Hello")
#show: ->
alert("Goodbye")
This allows control right down to the action level. When I came across your question I decided to package this solution into a gem as I have already used it in several projects. You can find it at: https://github.com/intrica/rails_document_ready
If you absolutely don't want a certain piece of initialization code to be run unless the current page is a specific controller/action, then you can try adding an empty element on the page with an id built from that info like "posts_index" using these two helpers:
"#{controller_name}_#{action_name}"
Then in your javascript you can wrap the code inside an if statement that checks for the existence of an element with the appropriate id.
edit: Here's an example of the js partial that I mentioned in the comments.
show.html.haml
= render 'map'
map.html.erb (I normally use haml but it's easier to write js in erb)
<script src='http://www.google.com/jsapi' type='text/javascript'></script>
<script type='text/javascript'>
...
</script>
It's probably not as clean as it could be and it doesn't get the benefits of being part of the asset pipeline but I don't mind because it's only something that gets included on a specific page.

ASP.NET MVC editor template javascript location

We have an editor template that contains approx 40 lines of jquery. I tried dropping this script into a <asp:Content> block to keep all of the javascript in one location within the page. However, I get the following error message content controls have to be top-level controls in a content page.
Is there any way to get this working so we don't have script dotted around our final output pages or could someone recommend the best practice for storing javascript used within ASP.NET MVC templates? At the moment I'm thinking of pulling the code into a separate file and referencing it within the master page but this means it gets pulled into every page which isn't really ideal.
Thanks in advance.
It would be easier for later maintenance, if you keep the javascript into a separate file and reference it where ever it is needed. Also, if you feel that placing all script into a single file will increase unnecessary loading of scripts, where not needed, then break the scripts into separate files based on functionality/modules in which it is useful etc. strategy and then reference them instead.
Also, it was said that always, keep/reference the scripts at the bottom of the page so that page loading will be faster.
as siva says, bottom of the page is the 'ideal'. however, as for seperate files. this is only going to be practical as long as you don't reference asp.net elements from the page - ie:
<asp:Content ContentPlaceHolderID="jsCode" ID="jsCode1" runat="server">
<script type="text/javascript">
$(document).ready(function() {
getPoundsData();
});
function getPoundsData() {
var id = $("#ID").val();
var URL = '<%=Url.Action("GetPounds", "FundShareholder")%>';
var params = { id: id };
if (id != null)
SendAjaxCache("#" + $("#ShareholderID option:selected").text() + " RSP#", URL, params, null, ListDataShareholderPounds);
}
function ListDataShareholderPounds(data) {
if (data.length != 0) {
$('#shareholderPounds').html("");
$('#shareholderPounds').show();
$('#shareholderPounds').html(data);
}
};
</script>
</asp:Content>
notice the:
var URL = '<%=Url.Action("GetPounds", "FundShareholder")%>';
part in the js. what 'we' do is to add a content section to the master page at the very bottom to hold our js stuff. however, this only works inside the ViewPage (aspx) object. the ascx pages are 'ignorant' of any master page content sections.
We are currently working on systemizing the process whereby we save 'partial' js files with asp.net references inside them and then inject them into the page-flow via a filterattribute. we're at an early stage with this but the nice thing about this approach is that the partial js is treated as a file and is therefore cached for future visits to that page.
anyway, that's our current approach, would be interested to discover if peeps are using any similar mechanisms to inject js that contains asp.net object references.
cheers...
[edit] - here's a heads up on the approach i'm talking about (this wasn't our original inspiration, but is quite similar, tho is webforms, rather than mvc) - http://www.west-wind.com/WebLog/posts/252178.aspx or this one which IS mvc: http://poundingcode.blogspot.com/2009/12/injecting-javasript-into-aspnetmvc-with.html.
Finally found the article that inspired our 'search' in this: ASP.NET MVC routing and paths is js files plus http://codepaste.net/p2s3po

Resources