How Javascript generates a source map of less and JS

Source: Internet
Author: User

Why is there a source map

CSS and JS scripts are becoming more and more complex, in order to solve the network bottleneck, most of the source code needs to be compiled, merged, compressed to apply to the actual environment. In order to reduce the use of network resources, the source code will generally be processed in the following ways:

Use CSS framework to merge compressed CSS files;
Use JS Merge plugin to reduce the number of network requests;
Compress JS file, reduce network occupation;

These three ways can effectively solve the actual problem, but at the same time in the run debugging process also brings trouble, because the CSS and JS are compressed conversion, when the error when we are difficult to locate the source code specific location. To solve this problem, Source map was born.

What is source map

The source map is equivalent to a mapping file, which provides the location of the converted code, corresponding to the original code. That is, in debugging the JS process, we can clearly see the current execution code corresponding to the source code of the specific location.

Supported browsers: The best support for source map currently is Chrome browser.

How to open Chrome's source map feature:
The first step, open the Developer Tools tool, select Menu view, Developer, Developer tools
Second step, select the Settings menu in the upper right corner
In the third step, select the General tab and check enable source maps.

How to use the source map in a project

There are generally two types of files that need to use source Map:css and JS. Because my project uses the Gulp environment. All I mainly introduce is the Gulp plugin that generates the source map.
To use gulp, use NPM to download the Gulp:gulp download first.

Before you download the plugin, create a project named Beautjs. The project directory structure is as follows:

Beautjs
----assets
----Less
----login.less
----main.less
----View
----Login.js
----Main.js

----Node_modules
----Gulpfile.js
----index.html
----Package.json

Next, look at how to generate the source map file.

Less how to generate a source map

CSS encoding, I used the less framework. To generate a source map file for CSS, you need to download the gulp-less and Gulp-sourcemaps plugins:
GULP-LESS:CSS coding Framework, using the introduction.
GULP-SOURCEMAPS:CSS generates a source map, using the introduction.

The next step is to configure the Gulpfile.js file, which should be introduced first using the Gulp plugin. Add code to the head of the file:

var gulp = require (' Gulp '); var sourcemaps = require (' gulp-sourcemaps '); var less = require (' gulp-less ');

Then add Gulp task tasks with the following code:

function () {    return gulp.src ([' assets/less/index.less '])        . Pipe (Sourcemaps.init ())         true})        . Pipe (Sourcemaps.write ("./"))        . Pipe (Gulp.dest (' dist/assets/ Styles ');});

Description: Index.less introduced all module less files under assets/less:

@import "Login""main";

So at compile time only compile index.less file. Once the configuration is complete, we can execute the command using the node. JS command-line tool:

Gulp Less

Finally, a dist folder is generated under the root directory with the following directory structure:

Dist
----assets
----INDEX.CSS
----Index.css.map

Open the Index.css file to view the code:

. Login-body {background:#fff} . Login-body. Login-item {background:#fff} . Main-body {background:#fff} . Main-body. Main-item {background:#fff} /* */

The following code can be seen in the last line of the file:

/**/

This contains the code is the key to source map, with this line of code, we can use the Chrome browser to see the index.css corresponding source code location. Of course, we can also remove the shift code when we're on the line project.
All of the styling resources are now available only with the introduction of the Index.css file in the index.html file.

JS how to generate a source map

JS file in the project is divided by the module, a module of a file. As the complexity of the project increases, the number of modules is increasing gradually. You can use the Gulp-concat plugin to merge JS files. The plugins you need to use are as follows:
Gulp-concat: File merging, Introduction to use.
Gulp-uglify:js file compression, Introduction to use.
GULP-SOURCEMAPS:JS generates a source map, using the introduction.

The next step is to configure the Gulpfile.js file, which is introduced first using the Gulp plugin. Add code to the head of the file:

var uglify = require (' gulp-uglify '); var concat = require (' Gulp-concat '); var sourcemaps = require (' gulp-sourcemaps ');

Then add Gulp task tasks with the following code:

function () {    return gulp.src (' view/*.js ')        true})        . Pipe (Concat ( ' index.min.js '). Pipe (        uglify ()). Pipe (        sourcemaps.write ('/')).        Pipe ( Gulp.dest (' Dist/view ');});

Currently, the Gulpfile.js file already has less and uglify two tasks, we can use the Gulp watch function, monitor the less and JS files are updated, there are updates immediately perform less and uglify two tasks. The complete code for the current Gulpfile.js file is as follows:

/** * Build Tasks*/varGulp = require (' Gulp '));varSourcemaps = require (' Gulp-sourcemaps '));varless = require (' gulp-less ');varUglify = require (' gulp-uglify '));varConcat = require (' Gulp-concat ')); Gulp.task (' Less ',function() {    returnGULP.SRC ([' Assets/less/index.less ']). Pipe (Sourcemaps.init ()). Pipe (Less ({compress:true}). Pipe (Sourcemaps.write ("./"). Pipe (Gulp.dest (' Dist/assets/styles '));}); Gulp.task (' Uglify ',function () {    returnGULP.SRC (' View/*.js '). Pipe (Sourcemaps.init ({loadmaps:true}). Pipe (Concat (' Index.min.js ') . Pipe (Uglify ()). Pipe (Sourcemaps.write (‘/‘). Pipe (Gulp.dest (' Dist/view '));}); Gulp.task ("Serve:build", [' less ', ' uglify '],function() {Gulp.watch ("Assets/less/**/*.less", [' less ']); Gulp.watch ("View/*.js", [' uglify ']);});

Once the configuration is complete, we can use the following command from the node. JS command-line tool:

Gulp Serve:build

Finally, create the Views folder under the root Directory Dist folder, the Dist directory structure is as follows:

Dist
----assets
----INDEX.CSS
----Index.css.map
----views
----Index.js
----Index.js.map

Open a. index.js file to view the source code:

function Login () {}function  main () {}//# Sourcemappingurl=index.min.js.map 

The following code can be seen in the last line of the file:

/**/

Now you only need to introduce the Index.js file in the index.html file. The source code is as follows:

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Beautjs</title>    <Linkrel= "stylesheet"href= "Dist/assets/styles/index.css" />    <Scripttype= "Text/javascript"src= "Dist/view/index.min.js"></Script></Head><Body></Body></HTML>

It's me. Test project directory:

Summarize

When the above steps are complete, we no longer have to worry about the reference to the JS file or CSS file, and the performance will improve when the project runs: reduce the number of network requests by merging files. Reduce network usage by compressing files.

Finally attach the test project git address: https://github.com/heavis/BeautJs.

If this article is helpful, please click on the attention in the lower right corner of the page. If you feel bad, also welcome to shoot bricks. Your evaluation is the power of the blogger! Next content, please look forward to!

How Javascript generates a source map of less and JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.