Move external libraries to wwwroot folder with gulp - javascript

I am using VS 2015 + ASP.net vnext + Angular 2 + Typescript + gulp.js. I have automated my scripts/**/*.ts files moving to the wwwroot/app folder. Now I want to do the same for my libraries like Angular 2. I want that a gulp process injects
angular.js inside index.html inside the <environment names="Development"> node;
angular.min.js inside index.html inside the <environment names="Production"> node.
Of course I want that this to happen for all my libs automatically, without having knowledge about a library:
<any>.min.js (production)
<any>.js (development)
The minification of any.js can be done by me.
Actually I would just have to regard all dependencies in package.json... but then I am lost.
Can my idea be done or does there maybe already exist a tool? Or should the workflow broken into more manual steps like I have to copy/paste a certain library?
Or is it possible to take the dependencies name and concat it with .js then search this file under the node_modules folder... (kind of hacky and not safe...)
UPDATE
Rephrase/Refine my question:
How can I automatically add my npm dependencies (not devDependencies) to the environment "Development" node when triggering a certain event like build/clear/etc...

There is a little tag helper for this, called asp-src-include.
Imagine the case where you have a handful of *.js files you want to include:
<script src="/app/app.js"></script>
<script src="/app/controller/controllerA.js"></script>
<script src="/app/controller/controllerB.js"></script>
<script src="/app/service/userservice.js"></script>
etc. You can include all of these with a single `ยด tag.
<script asp-src-include="~/app/**/*.js"></script>
So for Production/Development deployment your Razor markup may look like
<environment names="Development">
<script asp-src-include="~/app/**/*.js"></script>
</environment>
<environment names="Staging,Production">
<script asp-src-include="~/app/**/*.min.js"></script>
</environment>
For this you need the #addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" (starting with RC1 or RC2 it's ' #addTagHelper *, Microsoft.AspNet.Mvc.TagHelpers' - without the double-quotes ) declaration in your *.cshtml files or inside your _Layout.cshtml.
edit
There is an module called gulp-npm-files that does something similar, it copies all *.js files into the target folders. You can see it's source on GitHub in case you want write your own module to extend the functionality.
But that may not be exactly what you want, as the folders often contain multiple files, for example angular2 (AngularJS 2.0) contains dozen of files (*.js and *.ts), but you're mostly only interested in the compiled/minified ones, found in angular2/bundles/* like angular2.js, angular2.min.js or angular.dev.js.
The package.json of the particular dependency provides no information on where to find this compiled files. So I guess, there's no way to automate this unless you want to copy all of the files to wwwroot which makes no sense in my eyes, especially if you want to use asp-src-include, as it makes no difference on what it includes, so you want to minimize the number of *.js files in your wwwroot folder.
I guess the best you can do is to manually copy the dependencies via gulp task and then use asp-src-include to automatically include them into your razor generated html files.

So your problem is that you want to inject the scripts automatically into your HTML, right? You can use the Wiredep module for that.
And for copying the assets to an other folder, there are many modules to copy or link files from one folder to another. Gulp-copy is the first one i could find.

Related

Proper way to require external js and css libraries in ember js?

I have been playing around with ember 1.13 and I can see that in some online tutorials they require js and css via index.html while some uses ember-cli-build.js or brocfile.js for older versions. I find it requiring properly when I use ember-cli-build.js but then I am not sure what exactly the use of index.html
It depends.
If you have a ember-cli-plugin it will add the files to the vendor files by itself normally. Like with ember-cli-materialize.
If you are installing a random bower package like Ladda, you would need to add the files you need manually to ember-cli-build.js:
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
});
app.import('bower_components/ladda/dist/ladda-themeless.min.css');
app.import('bower_components/ladda/dist/spin.min.js');
app.import('bower_components/ladda/dist/ladda.min.js');
return app.toTree();
};
This will then be merged into your vendor.css and vendor.js which are linked to from index.html.
Also when you build the app the bower_components won't be available unless you've explicitly included something, so you cannot just link to them from index.html. It would also be a waste of network resources to include files separately. You shouldn't have to include anything in index.html unless it's an external resource.
brocfile.js is the old name for ember-cli-build.js since they've stopped using broccoli. Just use the newer one.

Is it possible not to mention all the script file paths in grunt?

I am using gruntjs and usemin task.
I added this to my html file:
<!-- build:js scripts/all.js -->
<script src="../../core/module.js"></script>
<script src="../../core/base/alerts/alert-item.js"></script>
<script src="../../core/base/alerts/alerts-list.js"></script>
<script src="../../core/base/base_model.js"></script>
<script src="../../core/base/cursor.js"></script>
<script src="../../core/...<another script>...."></script>
<script src="../../core/...<another script>...."></script>
<script src="../../core/...<another script>...."></script>
<script src="../../core/...<another script>...."></script>
<!-- endbuild -->
As you can see, all the scripts are located in ../../core How can I tell usemin to take first ../../core/module.js and then ../../core/**/* without mention each and every file?
Is this possible at all?
For grunt task configurations you can use globing patterns to build a file list dynamically.
Have a look at the two consecutive paragraphs on 'Globbing patterns' and 'Building the files object dynamically' in the gruntjs doc:
http://gruntjs.com/configuring-tasks#globbing-patterns
If you paste your usimin task configuration, it would be possible to help you building the right pattern
EDIT:
Based upon the comment and the fact you don't control all the code, an alternative to usemin would be to use a 'src' and 'dist' directory structure as demonstrated in the sample gruntfile to handle the bulk move/concat/uglify.
In the source HTML, reference the file that will be generated in your 'dist' directory by the grunt tasks.
Configure grunt-watch to copy, concat and uglify the files from 'src' upon a change.
When you need to test or upload to production, you can do it out of 'dist' without worrying about what scripts may have been added or changed in 'src'.
If you are just adding new files from the other project, you can create and call a 'build' task that does the same three tasks as grunt-watch does in #3.
If you poke around, you can find examples of this approach in several javascript frameworks that you can borrow and modify to your needs. This article might be useful.
Original:
Based upon this and your other question asked today, it sounds like usemin might not be the right tool for your need. Something like require.js would cut the number of script tags in your HTML but would shift the need to enumerate them to a different file/location...and your complaint seems to be with writing all of the scripts as a manifest/list in the code.
Grunt offers a way to handle files en masse, but that's best utilized when copying directories or doing other similar low-risk bulk work. Thus, you can find ways to get usemin to bulk load without logic, but I suggest it is generally bad practice to "load all the javascripts". ...but if that's what you want, I would ask you why a bulk concatenate and uglify isn't the answer.
The benefits of a manifest or explicitly listing the files become more visible as a project grows in size or complexity. An innocent mistake that adds/removes a file from the directory can cause confusion and the cause isn't instantly clear. Listing the files explicitly in the HTML would cause usemin to throw an error if one was missing in the directory and later, you can also audit the directory to see what is still lingering even though it is no longer used. Globbing them would not offer either of these benefits.
Without a manifest, things can be solved through judicious use of a VCS and a review of changes since the last commit...but that's not as easy or as fun as saying "Hey, script.js got deleted and that's causing usemin to barf so somebody owes me a beverage for replacing the file and getting the build working again!"

Serving bundled JavaScript with a pure AppHost implementation of ServiceStack

I would like to use ServiceStack as a pure AppHost implementation without using MVC. I want to use it to drive a Single Page App.
Serving the SPA's single HTML shell page is straightforward enough and I've found plenty of examples on doing that. However, I also need to serve a number of JavaScript files and I'm assessing the best way of doing this. I can simply put script tags in the HTML shell page but then I don't get the benefits of bundling and minification, and I would have to maintain this every time I add a new JavaScript file.
All these problems are solved with bundling solutions such as Cassette or ASP.NET MVC4 Bundles. But how would I use these with ServiceStack AppHost?
The ServiceStack.Bundler project is great but it seems to have dependencies on ASP.NET MVC, e.g. as a base for the HTML Helpers which render the JavaScript tags in the HTML.
I'd like to be able to do this without any dependency on MVC, if possible.
If you haven't taken a look at GruntJS yet, it's worth a look (http://gruntjs.com/). By creating some simple tasks, it can combine & minify your HTML, JS, and CSS and has no dependency on .NET. There are a lot of other really useful tasks available to GruntJS as well (js lint checks, JS unit test running, and tons more). You can easily setup different tasks for your environments as well (ie, don't combine/minify when deploying to dev server).
What it allows you to do is create a purely static HTML, CSS, and JS SPA, and you can manage that in a completely different solution/project than your ServiceStack AppHost.
So in your example, you'd just reference the scripts in your index.html file like you normally would and when you're ready to deploy to staging/production you'd run your grunt task which would bundle/minify your code for you and output the static html, min.css, and min.js files for you to some deployment directory. It's really powerful and flexible.
I used to use Bundler and I recently made the switch to GruntJS and I haven't looked back.
So, I don' think there is anything to need to do within ServiceStack's AppHost to use a 'bundling-and-minification' solution. To simplify the 'Bundling' process...
1 - 'Bundle' files from a folder(s) creating a new file(s)
2 - Reference the 'Bundled' file(s) from a View/Html
How to 'Bundle' files from a folder(s) creating a new file(s)
Cassette
Cassette seems to handle this process with 'some magic' (see web.config modifications for insight) that calls the Configure method of the CassetteBundleConfiguration class. Installing the Nuget package takes care of 'setup' for you.
ServiceStack.Bundler
ServiceStack.Bundler has a few different ways to handle this process...1) Manually with bundler.cmd, 2) A VS extension 3) Post Build Script 4) Short-cut key to an External Tool
Reference the 'Bundled' file(s)
You can do this however you like as long as you know the path of the file(s)
<link href="/Content/some.css" rel="stylesheet" type="text/css" />
<script src='some.js'></script>
Cassette offers some convenient rendering features
#Bundles.Reference('yourbundle')
#Bundles.RenderStylesheets()
#Bundles.RenderScripts()
ServiceStack.Bundler offers some as well (I think this is the code the depends on System.Web.MVC)
#Html.RenderJsBundle()
#Html.RenderCssBundle()
Note: These are just writing out the <link> and <script> HTML tags.
It seems neither Cassette nor Microsoft.AspNet.Web.Optimization (the bundling solution included with MVC4 projects by default) have dependencies on ASP.NET MVC. Therefore either solution can be made to work with an AppHost implementation of ServiceStack.
For Cassette:
It all works just fine if, from NuGet, you install:
ServiceStack.Host.AspNet
ServiceStack.Razor
Cassette.Aspnet
... and then use Cassette from a Razor 'cshtml' file as usual.
One small gotcha which did cause me to scratch my head for a few minutes:
The order in which the HttpHandlers are listed in your web.config is important. The ServiceStack.Host.AspNet package adds an HttpHandler path which uses a wildcard meaning any further HttpHandlers, such as that for Cassette.axd, are never reached.
Simply changing the order in my web.config from:
<httpHandlers>
<add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
<add path="cassette.axd" verb="*" type="Cassette.Aspnet.CassetteHttpHandler, Cassette.Aspnet" />
</httpHandlers>
to:
<httpHandlers>
<add path="cassette.axd" verb="*" type="Cassette.Aspnet.CassetteHttpHandler, Cassette.Aspnet" />
<add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
fixed the problem. I don't know if installing Cassette.Aspnet from Nuget first would have prevented this issue from occurring in the first place.
For Microsoft.AspNet.Web.Optimization:
From NuGet, you install:
ServiceStack.Host.AspNet
ServiceStack.Razor
Microsoft.AspNet.Web.Optimization
Having done this, you can use Microsoft.AspNet.Web.Optimization bundling and minification as normal.
I added a BundleConfig.cs file, followng the convention you'd find in a default MVC4 project. I then call BundleConfig.RegisterBundles(BundleTable.Bundles); from the ServiceStack AppHost file.
Thereafter, all #Scripts.Render() statements in Razor files work just fine.

Including JS files in Derby.js

I am trying to learn Derby.js and I am having a lot of trouble. I know I can include packages such as jQuery through npm and add it to the node_modules folder, but this isn't quite what I want to do. I want to be able to include these files like I do in normal HTML.
So I want to do something like <Head:> <script src="js/jquery.js"></script>. This does not work though because it cannot find the js directory. I expect this has something to do with the way node.js runs an app and that the app itself will not hold the js directory.
Any help would be appreciated!
Derby offers the Script: tag:
<Scripts:>
<script type="text/javascript" src="/components/jquery/jquery.js"></script>
The components directory is because of the usage of bower. Put the components directory into the public directory. According to the express FAQ, the static routes search below the given directory (which is public in derby's example application). Configure bower to put the files under public/components (Choose bower install directory).
The public directory is configured at lib/server/index.js: .use(gzippo.staticGzip(publicPath, {maxAge: ONE_YEAR})), where publicPath is configured above to path.join(root, 'public').
Be aware that the "idea behind the inline script is that it runs immediately, before any of the external scripts are loaded. This should only be used in rare cases where the script should run before the page is displayed in the browser, such as sizing something to the window or autofuocusing an element in browsers that don't support the "autofocus" attribute." Nate Smith in the derby google group.
Inline scripts should be placed in inline.js, located in the same directory as the application's index.js.
If you require jQuery to do something on the loaded page, following code snipped worked at my side (Firefox, Chrome) in inline.js:
window.onload = function() {
alert($(this));
}

Javascript requirejs in development but compiled in production

I'm beginning to evaluate javascript module tools like RequireJS for javascript modularization. This seems useful, especially during development, so I don't need to recompile all of the js files into mylib-<version>.js whenever I change one of the dependent files.
My app is distributed with both html and javascript files, and in production, I would like to use the compiled version of the javascript file.
So in development, my html file might look something like
<html>
<head>
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
</html>
But in production, I would expect it to look more like
<html>
<head>
<script src="mylib-1.0.js"></script>
</head>
</html>
I wouldn't think it production that there should be any need to reference requirejs if I am distributing a compiled file.
Is there a way to do this without having to manually change my html files before I distribute the app?
RequireJs has an optimization tool, which can help you to minify and concatenate your modules. It has a lot of options, and can be difficult to use, but it gets easier with a build tool like GruntJs or (especially) Yeoman, which uses GruntJs to build.
In both you can use the rjs task (which optimizes modules), but again Yeoman is a bit easier since it has generators which will configure it already for you:
// usemin handler should point to the file containing
// the usemin blocks to be parsed
'usemin-handler': {
html: 'index.html'
},
// rjs configuration. You don't necessarily need to specify the typical
// `path` configuration, the rjs task will parse these values from your
// main module, using http://requirejs.org/docs/optimization.html#mainConfigFile
//
// name / out / mainConfig file should be used. You can let it blank if
// you're using usemin-handler to parse rjs config from markup (default
// setup)
rjs: {
// no minification, is done by the min task
optimize: 'none',
baseUrl: './scripts',
wrap: true,
name: 'main'
},
In the index.html you just use a comment line to specify which js files should be minified/concatenated to which output file:
<!-- build:js scripts/amd-app.js -->
<script data-main="scripts/main" src="scripts/vendor/require.js"></script>
<!-- endbuild -->
In the example above, the modules will be concatenated to ONE file, named amd-app.js.
Edit:
This will be done by executing grunt from the command line. This will start a lot of useful tasks, which will build the project in a dist folder, but again this is highly adaptable.
The resulting index.html file (in dist) has only (if you want) one javascript file:
<script src="scripts/15964141.amd-app.js"></script>
My advice: use Yeoman to make life easier (at least for handling minification/concatenation).
First you have to compile your depency tree into one file using the r compiler. After that you can a striped down AMD loader like almond. At least you have to find a way to change the url in your index html.
Take a look at gruntjs which can automatize the whole thing, there a bunch task to like usemin that helps you with the process.

Categories