(from the transl.) On the technology of working with compiled code in the browser (SourceMap) there was already a detailed article ( translation ) about a year ago. Now this technology is persistently winning its place in the sun. For example, then conversations about mapping compilations were only conducted, and now from version 1.6.1 support for creating map files has been obtained by the Coffeescript compiler. Jetbrains Webstorm 6.0 / Phpstorm (March 2013) introduced SourceMap support for working with code . Typescript has support since version 0.8.1 (November 2012). Everyone understands that the time of manual work with the “assembler” on the front end passes, everyone needs to know where the code for the legs grows. We are not even talking about the initial application of the minifix code fixes - they are supported in UglifyJS, Closure Compiler and GWT (at a minimum). Speech is about JS and CSS code compilers.
So recently (in January 2013) this large tutorial article appeared, explaining with examples how the code card technology works. Although the first article was also detailed, but it would not hurt to have the second one translated, it describes the same thing in other words and illustrations, and proceeds to practice - to examples.
To pass the threshold from ordinary knowledge to experience always constitutes a certain barrier. Using training files, in order to see the results of creating code card files, we will occasionally get a working environment on our computer to build our own projects - all the compilers and minifiers we knew about, but were afraid to use, will be assembled and will only write its code on one of the sugar languages of the frontend, which were exotic until recently.
')
Please note that if you use the new version of the Grunt 0.4+ collector, then it will need several other settings than described in the article. More information about the transition from 0.3.9 to 0.4x is available at habrahabr.ru/post/170937 .
The author used screenshots from Mas. For Chrome, they are very different in the settings of the browser from the Windows version, so in some places screenshots from the Russian version of Chrome in Windows are added.
For cross-browser development, it is preferable to be able to work in any of the main systems. If there are no questions with Linux and MacOS, then it is important to check how well all the examples work under Windows. In the process of translation, examples were checked and refined in the Windows XP environment and on modern (as of April 2013) versions of programs. As a result, in 2 out of 5 examples, the improvements were made, laid out in the translation article as comments and additions. (The author of the article sent a message about the modifications.) They will help bring the examples to reality - both in terms of supporting new versions (especially Grunt 0.4 and Coffeescript 1.6.1), and confidence in the performance of all functions on Windows.
The next feature is the archive on the author’s github. Due to the fact that there are paths longer than 260 characters, it is not fully disclosed in WinRar (but this does not prevent us from using start files for examples that have shortcuts and run all the examples with them). To view and unpack (out of curiosity) the entire archive, which contains the files installed after the execution of all the examples, you need to use 7zip or another archiver other than WinRar.
There are a lot of comments, comments and alterations (hereinafter, they will be highlighted in the format of “citing” for convenience of distinction.) Nevertheless, this is not a new article, but a translation, with comments and taking into account local and Cyrillic features. Because you have to pay tribute to the good and rare organization of a lot of work in relation to the popularization of new technology.
But, since both articles on this topic - translated a year ago and under consideration - are outdated (many statements that do not correspond to the current moment), this, so to speak, translation touches upon all the issues so that the article becomes a modern practical guide on how to do it. the status of tools and browsers for today.
Since the examples will work modern version of Grunt (0.4), it is recommended to download not examples of the author , but updated examples of the translator . They contain both start-up files, as well as the results of installations and the work of examples, so that you can check the correctness and success of your actions - note the translation. .
(approx. transl. :) In this article at the end there is an example of SourceMap support for SASS in Firefox + Firebug. In addition, new about Firefox: Future of Firefox DevTools (17 Mar 2013) or in translation :
“CoffeeScript support. To implement it, we made support for SourceMap. Nick Fitzgerald demonstrated a debugger version supporting SourceMap and CoffeeScript
Nick's job helps support the minification of CSS and JS files. ”
*) wiki.mozilla.org/DevTools/Features/SourceMap
For Windows (from transl.) :
1) configuration and control (in the upper right corner) (F12);
2) in the developer window - “Settings” in the lower right corner;
3) select “General” and “Enable source maps” in the “Sources” block.
/start ├── index.html ├── /scripts │ ├── jquery.d.ts │ ├── script.coffee.coffee │ ├── script.js │ └── script.typescript.ts └── /styles ├── style.css └── style.sass
After testing and refining the examples to the current versions of the programs, the park of examples was supplemented with two options.
2.a GruntJS (0.4.x) with JSMin .
4.a CoffeeScript - not Redux, but original, version 1.6.2 .
The first one describes in detail the installation of the new version, which is very different from the current version 0.3.x up to February 2013. In the second, the launch and testing of the mapping, which appeared from version 1.6.1 in Coffeescript in February 2013 (since September 2012, this role has been played by a clone - Coffeescript Redux.)
(from transl.) The very first acquaintance with the code and the proposed method of switching options causes embarrassment. No, the author has done a lot of work and provides amazing technology. The article is perfectly framed. But the user interface is unexpectedly lame. The way of switching options through writing and deleting comments contradicts the ideology of the automated assembly approach - everything should be as manageable as possible. Display options - too. Nothing prevents switching options via the URL of the page. Let's write a switch, which, depending on the option parameter, will load this or that script into the anchor during page load. This is not a dynamic one-page download, although it is not far from it, but it is already better than switching in code.
var lHash = location.hash.substr(1).split('='); if(lHash && lHash.length ==2 && lHash[0] =='option') var optionName = lHash[1]; if(optionName && !parseInt(optionName)) optionName = {closure:1,jsmin:2,uglifyjs:3,coffeescript:4,typescript:5}[optionName.toLowerCase()]; console.log(optionName); optionName = optionName ||0; var loadScript; (loadScript = function(i){ var scr = document.createElement('SCRIPT'); scr.setAttribute('type', 'application/javascript'); scr.src ='scripts/script.' + ('|closure|jsmin-grunt|uglify|coffee.min|typescript.min'.split('|')[i]) +(i?'.':'') +'js'; document.getElementsByTagName('head')[0].appendChild(scr); })(optionName);
Now we got rid of a heap of comments in the code, the need to monitor them and switch. Adding an anchor # option = <number> or # option = <example_name> or the absence (or format error) of an anchor will cause the desired script to be executed from the options listed in scr.src. In the future, you can add your options under your own names.
And the switch of the background is somehow unfriendly - it requires sharpe before the code. The desire to use colors in verbal form is understandable, but few people are used to working with them. Let's correct:
var colr = $("#color").val().toUpperCase() , cL = colr.length; for(var i in cL) if(cL[i] <'0'|| cL[i] >'9'&& cL[i] <'A'|| cL[i] >'F') // hex- break; document.body.style.backgroundColor = (colr.charAt[0] !='#' && i < cL ?'':'#') + colr;
Probably, it looks complicated at first sight, but does not cause rejection due to primitiveness. Otherwise, it turns out that we are using the latest assembly technologies, and are unable to express the friendly interface in the code. Later we will be able to formulate our wishes in a more perfect code, invent for our codes not such a primitive loadScript and anchor reader, write all this in a coffee script and store it in our build library. After all, we come to the assembly of projects from the desire to disagree on the compromises of primitivity and simply display the complex logic of abstractions.
compiler.jar
in the directory with the scripts;scripts/
" directory and execute the command to create the script.closure.js
file that is optimized and ready for execution in production java -jar compiler.jar --js script.js --js_output_file script.closure.js
index.html
is associated with the created file by uncommenting “Option A.”index.html
in the browser and look at the Source panel in the developer’s tools, there is only a link to the optimized version of the script script.closure.js
; we have no way to link to the original code file with the desired indents. Now create a code map file by executing the following command in the scripts directory: java -jar compiler.jar --js script.js --create_source_map script.closure.js.map --source_map_format=V3 --js_output_file script.closure.js
--create_source_map
and --source_map_format
to create the map file script.closure.js.map
with Source Map version 3. But this is not all. To see the effect, add the source URLs to the end of the compiled script.closure.js
file script.closure.js
that it contains location data for them. //@ sourceMappingURL=script.closure.js.map
script.closure.js
. Although the browser uses an optimized file, the Source Map allows you to link it to the source code.Cyrillic users have the pleasure to notice another jamb, even two: one in the browser, the other in the compiler. The browser does not display UTF-8 characters in the mapped file:
The compiler is even worse: Cyrillic characters are considered an error, so they should be removed before compiling (if possible).
Grunt
differs from that described in version 0.3 of the article. - note of the translation.)JSMin
plugin using Grunt
.Grunt
and run ( alternative fresh description ) in the nodeJS gruntfile
called grunt.js
, located in the root of the " start/
" directory. $ npm install -g grunt $ npm view grunt version npm http GET https://registry.npmjs.org/grunt npm http 200 https://registry.npmjs.org/grunt 0.3.17 $ grunt init:gruntfile
How to work with Grunt 0.4.x
If you have an old version installed, but you want to upgrade it to 0.4.x, then the installation process will be different. First of all, remove the old version of Grunt 0.3.x (if it was installed as global).npm uninstall -g grunt
Let's take a closer look at setting up tasks in Grunt 0.4, since this will be one of the main build tools for a long time.
Now the Grunt module in the new version is divided into several modules - the core and plugins, in order to remove all application codes from the kernel. Several modules are involved in the installation.
Install the command line interface as a global grunt-cli module.npm install -g grunt-cli
To launch tasks in projects this is not enough - in each project you need to describe the tasks in the Gruntfile file. If earlier it was called grunt.js, then in the new version - Gruntfile.js or Gruntfile.coffee. The second required file in the project root is package.json with a list of dependencies used in npm (Node.js package manager).
In each task in the project folder a local grunt module is installed.Therefore, we will enter the “start /” folder on the command line and execute the specified command there. As in the 0.3.x version, the node_modules folder will appear and in it the grunt module folder.npm install grunt
Scattering the main code on projects is done with the aim of being able to run different versions of the search engine on one computer. grunt-cli is just a shell that runs a command in the desired project folder. ( gruntjs.com/getting-started )
Next, at the root of the project (“start /”) we prepareGruntfile.js
andpackage.json
.package.json
will be associated with your project and it describes dependencies - the needs for assembly plugins. For our project we will write:
{ "name": "colors", "version": "0.1.0", "devDependencies": { "grunt": "~0.4.1", "grunt-jsmin-sourcemap": "~1.5.6" } }
Instead of following clause 2 for version 0.3.x, you will need to performto pull up all dependencies fromnpm install grunt --save-dev
package.json
.
node_modules/grunt-jsmin-sourcemap
. $ npm install grunt-jsmin-sourcemap
grunt.js
(for version 0.4 - create Gruntfile.js
in "start /") so that it contains only the jsmin-sourcemap
- we will proceed as simply as possible: module.exports = function(grunt) { grunt.loadNpmTasks('grunt-jsmin-sourcemap'); grunt.initConfig({ 'jsmin-sourcemap': { all: { src: ['scripts/script.js'], dest: 'scripts/script.jsmin-grunt.js', destMap: 'scripts/script.jsmin-grunt.js.map' } } }); grunt.registerTask('default', 'jsmin-sourcemap'); };
E:\Projects\nodeJS\SourceMaps101\start> grunt
grunt.js
file (or Gruntfile.js
) . In case of successful result: Running "jsmin-sourcemap:all" (jsmin-sourcemap) task Done, without errors.
Next, we will add the execution results to the complete-ru directory in order to distinguish the author’s results from his own, which will be different mainly due to the new version of Grunt. This will help to verify your results with those verified on Windows when running the examples. - note of translation
"sources":["script.js"]
."sources":["scripts/script.js"]
was registered there "sources":["scripts/script.js"]
, so you should correct it with your hands. - comment perev.)Option B
to attach the generated script.grunt-jsmin.js file to index.html , and open it in a browser.(It is enough to call the modified index-ru.html file with an anchor: localhost / index-ru. Html # option = jsmin . - comment.)
In this example, we also obtained the source file mapping - no wonder we were torn through the installer installation. Further it will be easier, the main tool is in our pocket.
As you can see, here we are seeing jigs as well, which then, if used, will have to correct the texts with server scripts and version after version to keep track of the fixes. Such is it - development with tools in the early stages of readiness, and at the same time, very demanded by the market.
Grunt
and the jsmin-sourcemap
the build process creates 2 files: an optimized script with a link to the mapping file at the end and the code map file itself. Similar to the previous version, you will need both files to view the source.start
" directory:nocde_module/uglify-js
directory nocde_module/uglify-js
): $ npm install uglify-js -g $ npm view uglify-js version 2.2.3 $ cd scripts/
scripts
” directory, execute the command for creating an optimized version and map: uglifyjs --source-map script.uglify.js.map --output script.uglify.js script.js
(This time - no shamanism hands, everything works.)
index.html
uncomment the option "Option C".Since at the time of writing, the original Coffescript build by Jeremy Ashkenas did not support mapping, a mapping clone was used. In the version of Coffescript 1.6.1+ you can use the original language (which, however, does not reduce the other merits of the clone).
This clone, by the way, successfully collected $ 12,000 declared as a target on Kickstarter for further development.
start
" directory on the command line. In the next steps we will create a file of correspondences between the optimized and source files.script.coffee.coffee
in plain JS: $ coffee -c scripts/script.coffee.coffee
$ git clone https://github.com/michaelficarra/CoffeeScriptRedux.git coffee-redux $ cd coffee-redux $ npm install $ make -j test $ cd ..
script.coffee.js.map
, describing the correspondence between a simple JS and the original CoffeeScript. $ coffee-redux/bin/coffee --source-map -i scripts/script.coffee.coffee > scripts/script.coffee.js.map
script.coffee.js
file is the URL of the code card: //@ sourceMappingURL=script.coffee.js.map
script.coffee.js.map
file has the correct link to the file: "file":"script.coffee.coffee", and source file as "sources":["script.coffee.coffee"]
Work with coffeescript
Instead of working with a clone of a coffee script, let's make an example with the original compiler.
Items 1 and 2 remain unchanged.
Point 3 - skip.
four.coffee -o script.c -cm script.coffee.coffee
("-cm" are the abbreviated parameters "--compile" and "--map".)
5. Shoals.
With the creation of the output file - just a couple of bugs. 1) the script.coffee.js file is not created — instead of it — script.js, overwriting the variant from the first examples. Therefore, we create a file in a separate directory (there is no way to create a file with a different name within the same command if we do not consider threads in the OS); 2) if there is no directory, a “left” empty directory "/ -p /" is created along with the required one.
To test the paths, it is worth running this intermediate result, which will look like the 6th example - uncompressed coffeescript, and check the correctness of the paths in it.
If we create a code map with one command (and not two separate), then at the end of the compiled file there is a comment likeIt turned out that Chrome reads a comment of this kind.
/* //@ sourceMappingURL=script.map */
And “file”: “script.js” and other paths in the code map did not need to be changed either. There is:
"file": "script.js", "sourceRoot": "..", "sources": [ "script.coffee.coffee" ],
To run, they chose such a strange directory name, script.c, in advance so that it would fit well into the previously built script.
var lHash = location.hash.substr(1).split('='); if(lHash && lHash.length ==2 && lHash[0] =='option') var optionName = lHash[1]; if(optionName && !parseInt(optionName)) optionName = {closure:1,jsmin:2,uglifyjs:3,coffeescript:4,typescript:5,'coff':6}[optionName.toLowerCase()]; console.log(optionName); optionName = optionName ||0; var loadScript; (loadScript = function(i){ var scr = document.createElement('SCRIPT'); scr.setAttribute('type', 'application/javascript'); scr.src ='scripts/script.'+ ('|closure|jsmin-grunt|uglify|coffee.min|typescript.min|c/script'.split('|')[i]) +(i?'.':'') +'js'; document.getElementsByTagName('head')[0].appendChild(scr); })(optionName);
With parameter 6 orcoff
script will be read from thescripts/script.c/script.js
path. We see that everything works without patches, despite the creation of an intermediate file in the directory. Good job compiler author!
This is the coffeescript in Chrome debugging.
It is evident that Chrome still does not completely understand utf-8. Installationscr.setAttribute('charset', 'utf-8');
also does not help.
scripts
": $ cd scripts/ $ uglifyjs script.coffee.js -o script.coffee.min.js --source-map script.coffee.min.js.map --in-source-map script.coffee.js.map
For our example branch, the command view is
uglifyjs script.c/script.js -o script.coffee.min.js --source-map script.coffee.min.js.map --in-source-map script.c/script.map
"file":"script.coffee.min.js"
"sources":["script.coffee.coffee"]
We write in the address bar
http://localhost/#option=coffeescript
... And we see that something is wrong with the path in the file."sources":["script.coffee.coffee"]
should work, but not work. But I managed to see the source file by writing (it took to rediscover the browser)
"sources":["/scripts/script.coffee.coffee"]
Still, complicated paths with thescript.c
directory had anscript.c
, and the minifier in conjunction did not work as it was, had to be edited, and this edit looks more like a raw product hack.
script.typescript.ts
and jquery.d.ts
.Install Typescript:npm install -g typescript
$ tsc script.typescript.ts -sourcemap
script.typescript.js
file with a link at the end: //@ sourceMappingURL=script.typescript.js.map
And in the same command, the script.typescript.js.map
map file is created.Crhbgn complained about the inconsistency of some parameters for jQuery and for one in our code:/script.typescript.ts(7,8): The property 'keyCode' doesn’t exist for the value of type 'JQueryEventObject'
But he took the job; The file that is actually Javascript processed.
To see changes to the source code, you need to clear the browser cache.
$ uglifyjs script.typescript.js -o script.typescript.min.js --source-map script.typescript.min.js.map --in-source-map script.typescript.js.map
index.html
point to the correct script file: scripts/script.typescript.min.js
and open it in a browser.No errors related to the compiler and minifiers were noticed on this simple code. Source codes and mapping work without manual edits of service files.
Dev Tools -> Setting -> Experiments -> Check “Support for SASS”
.styles
" directory on the command line. This will precede each rule set with @media -sass-debug-info
$ cd styles/ $ sass --debug-info --watch style.sass:style.css
*.map
file, it will contain a mapping of information between the source file and the resulting one. The structure, as a rule, is contained in the JSON format according to the specification of version 3 cards. Usually, there are 5 properties:
: Sayanee Basu, . Ruby . — .
, « » — . ; — nodeJS . , , , — , nodeJS. . , , - , , .
( , Firefox .)
? Coffeescript, . , 2 , , JS.
Grunt, , SASS — . , , , . , — , , , .
, , , nodeJS, - .
, Windows + nodeJS.
1) Using Source Maps with TypeScript , Aaron Powell, Oct 3 2012;
2) github.com/mozilla/source-map — This is a library to generate and consume the source map format .
3) Happy debugging with JavaScript source maps by James Allardice, 25 January 2013.
4) bower.io — Twitter.
5) kevinpelgrims.com/blog/2011/12/28/building-coffeescript-with-sublime-on-windows
6) sourcemap.litcoffee .
7) github.com/evanw/node-source-map-support
8) , (2013-05)
Source: https://habr.com/ru/post/178743/
All Articles