I'm trying to minify and concatenate require modules together into one file.
For example, if I have a file called article.js like the following:
define(["jquery","flexslider","share_div"],function(){});
I want all of those dependencies to be combined and minified into one file.
I have the following in my build script, but it's not combining files together, just minifying.
This is my build.js file:
{
"appDir": "../js",
"baseUrl": "../js",
"dir": "../www-build",
"mainConfigFile": "../js/common.js",
"modules": [
{
"name": "common"
},
{
"name": "page/article",
"exclude": ["common"]
}
],
"paths": {
"jquery": "empty:",
"jquery_ui": "empty:",
"twitter_bootstrap": "empty:"
}
}
My understanding of Require and the build script may be wrong, but I envisioned that files would be concatenated together.
Any guidance would be appreciated.
To also minify the nested dependencies of the individual modules that are traced as dependencies, specify this additonal property as part of your build file: findNestedDependencies: true. (See line 318-324 of the full RequireJS doc.)
This is if articles.js is a dependency found in common.js and you are tracing through common.js to build a concatenated and minfied file. I am not sure about the lack of concatenation if you are just trying to build the individual module itself.
The build.txt file you've included in a comment (the comment I'm referring to has been deleted by Andy after I wrote my answer) is a bit hard to read since it has not been included as preformatted code. From what I can see in the file you've provided, r.js does indeed concatenate the dependencies of article.js into one file. So it appears that you've solved your original question somehow.
As so why your output is not appearing in the right directory, I can only speculate. The build.js file you've shown in your question is set to put everything in ../www-build, however your build.txt file shows the output being stored in ../js. Here's the speculation part: sometimes when we are in the midst of trying to find solutions, we make changes here and there and lost track of where we were. That certainly happened to me. What I do then is clean my development tree (remove the builds), inspect my build configuration to make sure that what I think is used is indeed used and rerun the build.
Related
We have an application that has multiple environments and is about to have multiple vendors. I understand that the typical flow is to run webpack --env.NODE_ENV=myenvironment, however, this will become highly inefficient very quickly.
Ultimately, the simplicity of my goal is to copy the environment.json file into the output folder and use it so that I can perform transformations in Octopus Deploy rather than having to run multiple builds.
In other words, I'd like to utilize a single environment.json file for the purpose of providing variable substitutions in Octopus Deploy. Here's a sample environment.json:
{
"production": false,
"baseUrl": "http://myapp.com",
"appId": "MyAppId"
}
Now in AngularJS code, I'm configuring constants that utilize these values:
import * as environment from '../../environment.json';
console.log(environment.baseUrl); // http://myapp.com
angular.module('app')
.constant('environment', environment);
So far, so good.
The problem is that now if I modify the values inside of dist/environment.json (note this is in the output folder), it does not update the values. For example, if I change the value of baseUrl to http://myapp-dev.com, the console.log will still print http://myapp.com.
Here's the relevant code in my webpack.config.js:
Rules
...
{
test: /\.json$/,
use: 'json-loader',
exclude: [/environment\.json$/]
},
...
Plugins
...
new CopyWebpackPlugin([{
from: 'environment.json'
},
...
The above code successfully copies the environment.json file to the output folder, but the rest of the code in the output folder is NOT using it. For whatever reason it appears to still be coupled with webpack.
CopyWebpackPlugin just copies a file - nothing more happens here and Webpack won't use that internally. The static JSON import is most likely part of you main bundle js.
Instead of trying to dynamically replace some parts of the build define a external module. This way you have the flexibility to provide whatever globals you want to the browser environment and webpack will know where to find them during runtime.
I have a build that includes the following scripts in my angular.json file:
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/lodash/index.js",
"node_modules/backbone/backbone.js",
"node_modules/jointjs/dist/joint.js"
]
As you can see there, I'm including node_modules/jointjs/dist/joint.js, which is the non-minified version of the jointjs library.
However, when I run ng serve it continues to bundle the joint.min.js file, which resides in the same directory as join.js.
I would like to use the non-minified version while in dev, to help me track issues with params I'm passing to the library.
How can this be accomplished?
Thanks!
To achieve this you can redirect to the correct file in the tsconfig.json file like this.
"paths": {
"jointjs": [
"node_modules/jointjs/dist/joint.js"
]
}
Also I don't think you really need to have anything at all in scripts. What you put here gets included in another output file scripts.js which is separate from vendor.js and is meant if you want to include some scripts like the includes in a webpage. In this case all the related libraries get included by joint.js automatically and go into vendor.js so there is no need to include them again. Here is the documentation about global scripts in angular-cli.
Another option is that you edit the package.json file in the jointjs npm module (npm_modules/jointjs/package.json) directly and change the entry "main": "./dist/joint.min.js", to "main": "./dist/joint.js",. This is a bit of a hack since you are changing the npm package.
Maybe I'm trying to do something silly, but I've got a web application (Angular2+), and I'm trying to build it in an extensible/modular way. In particular, I've got various, well, modules for lack of a better term, that I'd like to be able to include or not, depending on what kind of deployment is desired. These modules include various functionality that is implemented via extending base classes.
To simplify things, imagine there is a GenericModuleDefinition class, and there are two modules - ModuleOne.js and ModuleTwo.js. The first defines a ModuleOneDefinitionClass and instantiate an exported instance ModuleOneDefinition, and then registers it with the ModuleRegistry. The second module does an analogous thing.
(To be clear - it registers the ModuleXXXDefinition object with the ModuleRegistry when the ModuleXXX.js file is run (e.g. because of some other .js file imports one of its exports). If it is not run, then clearly nothing gets registered - and this is the problem I'm having, as I describe below.)
The ModuleRegistry has some methods that will iterate over all the Modules and call their individual methods. In this example, there might be a method called ModuleRegistry.initAllModules(), which then calls the initModule() method on each of the registered Modules.
At startup, my application (say, in index.js) calls ModuleRegistry.initAllModules(). Obviously, because index.js imports the exported ModuleRegistry symbol, this will cause the ModuleRegistry.js code to get pulled in, but since none of the exports from either of the two Module .js files is explicitly referenced, these files will not have been pulled in, and so the ModuleOneDefinition and ModuleTwoDefinition objects will not have been instantiated and registered with the ModuleRegistry - so the call to initAllModules() will be for naught.
Obviously, I could just put meaningless references to each of these ModuleDefinition objects in my index.js, which would force them to be pulled in, so that they were registered by the time I call initAllModules(). But this requires changes to the index.js file depending on whether I want to deploy it with ModuleTwo or without. I was hoping to have the mere existence of the ModuleTwo.js be enough to cause the file to get pulled in and the resulting ModuleTwoDefinition to get registered with the ModuleRegistry.
Is there a standard way to handle this kind of situation? Am I stuck having to edit some global file (either index.js or some other file it references) so that it has information about all the included Modules so that it can then go and load them? Or is there a clever way to cause JavaScript to execute all the .js files in a directory so that merely copying the files it would be enough to get them to load at startup?
a clever way to cause xxJavaScriptxx Node.js to execute all the .js files in a directory:
var fs = require('fs') // node filesystem
var path = require('path') // node path
function hasJsExtension(item) {
return item != 'index.js' && path.extname(item) === '.js'
}
function pathHere(item) {
return path.join('.', item)
}
fs.readdir('./', function(err, list) {
if (err) return err
list.filter(hasJsExtension).map(pathHere).forEach(require) // require them all
})
Angular is pretty different, all the more if it is ng serve who checks if your app needs a module, and if so serves the corresponding js file, at any time needed, not at first load time.
In fact your situation reminds me of C++ with header files Declaration and cpp files with implementation, maybe you just need a defineAllModules function before initAllModules.
Another way could be considering finding out how to exclude those modules from ng-serve, and include them as scripts in your HTML before the others, they would so be defined (if present and so, served), and called by angular if necesary, the only cavehat is the error in the console if one script tag is not fetched, but your app will work anyway, if it supposed to do so.
But anyway, it would be declaring/defining those modules somewhere in ng-serve and also in the HTML.
In your own special case, and not willing to under-evalute ng-serve, but is the total js for your app too heavy to be served at once? (minified and all the ...), since the good-to-go solution may be one of the many tools to build and rebuild your production all.js from your dev js folder at will, or like you said, with a drag&drop in your folder.
Such tool is, again, server-side, but even if you only can push/FTP your javascript, you could use it in your prefered dev environment and just push your new version. To see a list of such tools google 'YourDevEnvironment bundle javascript'.
To do more with angular serve and append static js files under specific conditions, you should use webpack so the first option i see here is eject your webpack configuration and after that you can specify what angular should load or not.
With that said, i will give an example:
With angular cli and ng serve any external javascript files you wanna include, you have to put them inside the scripts array in the angular-cli.json file.However you can not control which file should be included and which one not.
By using webpack configuration you can specify all these thing by passing a flag from your terminal to the webpack config file and do all the process right there.
Example:
var env.commandLineParamater, plugins;
if(env.commandLineParamater == 'production'){
plugins = [
new ScriptsWebpackPlugin({
"name": "scripts",
"sourceMap": true,
"filename": "scripts.bundle.js",
"scripts": [
"D:\\Tutorial\\Angular\\demo-project\\node_moduels\\bootstrap\\dist\\bootstrap.min.js",
"D:\\Tutorial\\Angular\\demo-project\\node_moduels\\jquery\\dist\\jquery.min.js"
],
"basePath": "D:\\Tutorial\\Angular\\demo-project"
}),
]}else{
plugins = [
new ScriptsWebpackPlugin({
"name": "scripts",
"sourceMap": true,
"filename": "scripts.bundle.js",
"scripts": [
"D:\\Tutorial\\Angular\\demo-project\\node_moduels\\bootstrap\\dist\\bootstrap.min.js"
],
"basePath": "D:\\Tutorial\\Angular\\demo-project"
}),
]
}
then:
module.exports = (env) => {
"plugins": plugins,
// other webpack configuration
}
The script.js bundle will be loaded before your main app bundle and so you can control what you load when you run npm run start instead of ng-serve.
To Eject your webpack configuration, use ng eject.
Generally speaking, when you need to control some of angular ng-serve working, you should extract your own webpack config and customize it as you want.
The HTML starter kit pro for Durandal contains the following grunt task for optimizing a build:
durandal: {
main: {
src: ['app/**/*.*', 'lib/durandal/**/*.js'],
options: {
name: '../lib/require/almond-custom',
baseUrl: requireConfig.baseUrl,
mainPath: 'app/main',
paths: mixIn({}, requireConfig.paths, {
'almond': '../lib/require/almond-custom.js'
}),
exclude: [],
optimize: 'none',
out: 'build/app/main.js'
}
}
}
I have some concerns about it which I need your help sorting out:
Script file redundancy. The build process keeps the lib folder with scripts like jQuery, bootstrap etc. Why? If you look at the built build/app/main.js is has added all those scripts. Which leads me to the following question:
If I remove the lib folder, everything works, except for the fact that I get a require is not defined in the console. The code still looks for lib/require/require.js which can be solved by simply adding it there. However, isn't this what almond is all about? It's included in the built build/app/main.js file. As far as I knew, Almond is a light weight replacement for require to be used in optimized files.
To reproduce the issues you can simply run the "Quick start" provided in the link at the top.
Yes, You are right that main.js includes everything needed to run the app. The reason You are getting require is not defined is because, if you closely look at the index.html file you will see that the index.html refers looks for the file in /lib/require folder and loads our main.js file through it. there is another line right below that in index.html which is commented, you can just uncomment that and it should just work even if you remove lib directory.
The only errros that you will get by removing the /lib directory after uncommenting <script src="app/main.js"></script> line and commenting <script src="lib/require/require.js" data-main="app/main"></script>.
Hope it helps.
I have a directory like below:
/folder/b.js
/folder/jQuery.js
/folder/a.js
/folder/sub/c.js
I want to minify all these js files in one js file in order:
jQuery.js -> a.js -> b.js -> c.js
Q:
1.How can I do it via grunt-contrib-uglify?(In fact, there are lots of files, it is impractical to specify all source filepaths individually)
2.btw, How can I get unminified files when debug and get minified single file when release and no need to change script tag in html(and how to write the script tag)?
Good questions!
1) Uglify will reorder the functions in the destination file so that function definitions are on top and function execution on bottom but it seems that it will preserve the order of the function executions.
This means that the function jQuery runs to define its global functions will be put first if you make sure jQuery is mentioned first in Uglify's config in the Gruntfile.
I use this config:
uglify: {
options: {
sourceMap: true
},
build: {
files: {
'public/all.min.js': ['public/js/vendor/jquery-1.10.2.min.js', 'public/js/*.js'],
}
}
}
2) I don't think there is one definite way to accomplish this. It depends on what web framework, templating framework and what kind of requirements you have. I use express + jade and in my main jade layout I have:
if process.env.NODE_ENV === 'production'
script(src='/all.min.js')
else
script(src='/js/vendor/jquery-1.10.2.min.js')
script(src='/js/someScript.js')
script(src='/js/otherScript.js')
In my package.json I have:
"scripts": {
"postinstall": "grunt"
},
This means that when I run npm install on deploy (on Heroku) grunt is run to minify/concat files and when the app is started with NODE_ENV=production the minified client side javascript is used. Locally I get served the original client side javascripts for easy debugging.
The two downsides are:
I have to keep the two lists of script files in sync (in the Gruntfile and in the layout.js) I solve this by using *.js in the Gruntfile but this may not suite everyone. You could put the list of javascripts in the Gruntfile and create a jade-template from this but it seems overkill for most projects.
If you don't trust your Grunt config you basically have to test running the application using NODE_ENV=production locally to verify that the minification worked the way you intended.
This can be done using the following Grunt tasks:
https://github.com/gruntjs/grunt-contrib-concat concatenates
files
https://github.com/gruntjs/grunt-contrib-uglify minifies
concatenated files
EDIT
I usually run all my files through a Grunt concatenation task using grunt-contrib-concat. Then I have another task to uglify the concatenated file using grunt-contrib-uglify.
You're probably not going to like this, but the best way is to define your js source files as AMD modules and use Requirejs to manage the order in which they load. The grunt-contrib-requirejs task will recurse your dependency tree and concatenate the js files in the necessary order into one big js file. You will then use uglify (actually r.js has uglify built-in) to minify the big file.
https://github.com/danheberden/yeoman-generator-requirejs has a good example gruntfile and template js files to work from.
EDIT
I've recently started using CommonJS modules instead of AMD since it's much closer to the ES6 module spec. You can achieve the same results (1 big complied+concatenated js file) by running commonjs modules through Browserify. There are plugins for both grunt and gulp to manage the task for you.
EDIT
I'd like to add that if your site is written using ES6 that Rollup is the best new concatenating package. In addition to bundling your files, it will also perform tree shaking, removing parts of libraries you use if included via an import statement. This reduces your codebase to just what you need without the bloat of code you'll never use.
I don't think you can do this with the uglify task alone, but you have a multitude of choices which might lead to your desired outcome.
A possible workflow would be first concatenating (grunt-contrib-concat) the files in order into one single file, and put this concatenated file through uglify. You can either define the order for concat in your Gruntfile, or you use on of those plugins:
First one would be https://github.com/yeoman/grunt-usemin, where you can specify the order in your HTML file, put some comments around your script block. The Google guys made it and it's pretty sweet to use.
Second one would be https://github.com/trek/grunt-neuter, where you can define some dependencies with require, but without the bulk of require.js. It requires changes in your JS code, so might not like it. I'd go with option one.
I ran into the same issue. A quick fix is just to change the filenames - I used 1.jquery.min.js, 2.bootstrap.min.js, etc.
This might be only remotely related to your question but I wanted something similar. Only my order was important in the following way:
I was loading all vendor files (angular, jquery, and their respective related plugins) with a wildcard (['vendor/**/*.js']). But some plugins had names that made them load before angular and jquery. A solution is to manually load them first.
['vendor/angular.js', 'vendor/jquery.js', 'vendor/**/*.js]
Luckily angular and jquery handle being loaded twice well enough. Edit: Although it's not really the best practice to load such large libraries twice, causing your minified file unnecessary bloat. (thanks #Kano for pointing this out!)
Another issue was client-js the order was important in a way that it required the main app file to be loaded last, after all its dependencies have been loaded. Solution to that was to exclude and then include:
['app/**/*.js', '!app/app.js', 'app/app.js']
This prevents app.js from being loaded along with all the other files, and only then includes it at the end.
Looks like the second part of your question is still unanswered. But let me try one by one.
Firstly you can join and uglify a large number of js files into one as explained by the concat answer earlier. It should also be possible to use https://github.com/gruntjs/grunt-contrib-uglify because it does seem to have wildcards. You may have to experiment with 'expand = true' option and wildcards. That takes care of your first question.
For the second part, say you joined and uglified into big-ugly.js
Now in your html you can add following directives:
<!-- build:js:dist big-ugly.js -->
<script src="js1.js"></script>
<script src="js2.js"></script>
<!-- etc etc -->
<script src="js100.js"></script>
<!-- /build -->
And then pass it through the grunt html preprocessor at https://www.npmjs.com/package/grunt-processhtml as part of your grunt jobs.
This preprocessor will replace the entire block with
<script src="big-ugly.js"></script>
Which means that the html file with be semantically equivalent - before and after the grunt jobs; i.e. if the page works correctly in the native form (for debugging) - then the transformed page must work correctly after the grunt - without requiring you to manually change any tags.
This was #1469's answer but he didn't make it clear why this works. Use concat to put all js files into one, this module does this in the order of file names, so I put a prefix to the file names based on orders. I believe it even has other options for ordering.
concat: {
js: {
options: {
block: true,
line: true,
stripBanners: true
},
files: {
'library/dist/js/scripts.js' : 'library/js/*.js',
}
}
},
Then use uglify to create the minified ugly version:
uglify: {
dist: {
files: {
'library/dist/js/scripts.min.js': [
'library/js/scripts.js'
]
},
options: {
}
}
},
If your problem was that you had vendors which needed to be loaded in order (let's say jquery before any jquery plugins). I solved it by putting jquery in its own folder called '!jquery', effectively putting it on top of the stack.
Then I just used concat as you normally would:
concat: {
options: {
separator: ';',
},
build: {
files: [
{
src: ['js/vendor/**/*.js', 'js/main.min.js'],
dest: 'js/global.min.js'
}
]
}
},