前端工具安装简述

前言

  虽然一直有写前端,而且水平自认上升很快,但是仍然没有玩过模块化开发。

  对于前端的这些工具也没有接触过,平时一般都是vs和vs code就搞定了,为了搞一搞模块化开发,准备来玩一下这些前端工具。

  所以写写这些前端工具的安装步骤,记录一下以后忘了也能用,如果能帮到别人就更好了。

1、NPM和Node.js的安装

  安装node.js后,自动就安装了npm,所以这里两者写到一起了。

  nodejs的下载地址:

  https://nodejs.org/en/download/

  这种东西给个下载地址就好了,根据自己电脑类型安装,做程序员的也没有电脑小白,下一步就不说了。

  npm下载源的配置

  npm在这里被我理解为一个下载工具,而下载的地址为https://www.npmjs.com 。

  只不过在国内访问不稳定,因此建议使用国内镜向站点https://npm.taobao.org 。

  在cmd.exe中,运行以下命令即可:

npm --registry https://registry.npm.taobao.org info underscore

  或者找到Nodejs安装文件夹中的npmrc文件,在该文件中加入

registry = https://registry.npm.taobao.org

2、gulp的安装

  gulp用来优化前端工作流程。

  全局安装gulp:  

npm install gulp -g

  输入gulp -v可以查看到相应版本

  使用到项目中:

  以下是我用vs code自己建的一个项目:

  

  命令行cd到自己建的项目文件夹,然后npm init即可生成自己的package.json,这是自己项目的每个项目的一个描述文件,定义了这个项目所需要的各种模块,以及项目的配置信息(比如名称、版本、许可证等元数据)。

  将gulp安装到项目中

npm install gulp --save-dev

  安装后:

  

  此时项目中多了node_modules这个文件夹,同时package.json中自动写入了devDependencies字段,并在该字段下填充了gulp模块名。

  

  接下来安装上面gulp中可用的一堆插件

npm install --save-dev gulp-uglify gulp-concat gulp-imagemin gulp-htmlmin gulp-clean-css gulp-rev-append gulp-autoprefixer

  安装后:

  

 

  gulp-uglify为压缩js文件,gulp-concat为合并打包文件,gulp-imagemin为压缩图片,gulp-htmlmin为压缩html,gulp-clean-css压缩css文件,gulp-rev-append为添加版本号。

  实际上.NET MVC的bundle继承了上面这些功能,所以用.net进行开发貌似完全用不到,不过想来别的语言也许应该还是需要的。

  而gulp-autoprefixer是根据设置浏览器版本自动处理浏览器前缀,gulp-less插件将less文件编译成css,当有less文件发生改变自动编译less,并保证less语法错误或出现异常时能正常工作并提示错误信息。

  肯定还是有一些别的功能的插件,这只是我暂时了解到的几个,如果有其它好用的也希望有大神能留言告诉我一下。

  编写gulpfile.js文件

  如果要用这些插件,那么还要在根目录下加一个gulpfile.js配置文件,以下为我自己的测试项目:

  

  根据测试项目写的配置文件:

/*引入gulp及相关插件 require('node_modules里对应模块')*/
var gulp = require('gulp');
var minifyCss = require("gulp-clean-css"),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    htmlmin = require('gulp-htmlmin'),
    rev = require('gulp-rev-append'),
    autoprefixer = require('gulp-autoprefixer'),
    less = require('gulp-less');
//压缩html,并给页面的引用添加版本号,清除页面引用缓存
gulp.task('minifyHtml', function() {
    var options = {
        removeComments: true, //清除HTML注释
        collapseWhitespace: true, //压缩HTML
        collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true, //删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
        minifyJS: true, //压缩页面JS
        minifyCSS: true //压缩页面CSS
    };
    gulp.src('examples/*.html')
        .pipe(htmlmin(options))
        .pipe(rev())
        .pipe(gulp.dest('dist/html'));
});
//压缩图片
gulp.task('minify-img', function() {
    gulp.src('src/img/*.{png,jpg,gif,ico}')
        .pipe(imagemin())
        .pipe(gulp.dest('dist/img/'));
});
//编译less
gulp.task('handleLess', function() {
    gulp.src('src/less/*.less')
        .pipe(less())
        .pipe(gulp.dest('src/css'));
});
//设置浏览器版本自动处理浏览器前缀,并压缩css
gulp.task('minify-css', function() {
    gulp.src('src/css/*.css')
        .pipe(autoprefixer({
            browsers: ['last 2 versions', 'Android >= 4.0'],
            cascade: true, //是否美化属性值 默认:true 像这样:
            //-webkit-transform: rotate(45deg);
            //        transform: rotate(45deg);
            remove: true //是否去掉不必要的前缀 默认:true 
        }))
        .pipe(minifyCss())
        .pipe(gulp.dest('dist/css/'));
});
//打包并压缩js
gulp.task('minify-script', function() {
    gulp.src('src/js/*.js')
        .pipe(concat('helloworld.js')) //打包
        .pipe(uglify()) //压缩
        .pipe(gulp.dest('dist/js/'));
});
gulp.task('default', ['minifyHtml', 'minify-img', 'handleLess', 'minify-css', 'minify-script']);

   运行gulp完成前端构建

   根据上面的配置我们可以在命令行输入 :

gulp minify-script

   这就只打包压缩JS文件,也可以输入:

gulp minify-script

   这样就完成我们所有的构建工作。

  进一步的学习可以转到:http://www.gulpjs.com.cn/

3、webpack的安装

  webpack是一个前端模块化方案,只不过是本地的,而类似requireJs和sea.js是在线模块化方案。

  有了上面安装gulp的经验webpack就简单多了。

  安装webpack :

npm install webpack -g

  接下来增加package.json配置文件,也就是

npm init

  只不过我们前面配置了,那么直接下一步:

npm install webpack --save-dev

  同样这个webpack也会加到node_modules文件夹中。

那么来一段简单的前端示例,使用webpack来实现前端模块化,我有两个文件:

hello.js

window.resize = function() {
    console.info("我resize了!");
}

helloApp.js

var hello = require('./hello.js');
console.log(hello);

虽然不清楚语法,但是大概也能明白,helloApp.js引用了hello.js。

运行

 webpack src/js/helloApp.js dist/js/helloApp.Main.js

然后生成的helloApp.Main.js是下面这个样子:

/******/ (function(modules) { // webpackBootstrap
/******/     // The module cache
/******/     var installedModules = {};
/******/
/******/     // The require function
/******/     function __webpack_require__(moduleId) {
/******/
/******/         // Check if module is in cache
/******/         if(installedModules[moduleId]) {
/******/             return installedModules[moduleId].exports;
/******/         }
/******/         // Create a new module (and put it into the cache)
/******/         var module = installedModules[moduleId] = {
/******/             i: moduleId,
/******/             l: false,
/******/             exports: {}
/******/         };
/******/
/******/         // Execute the module function
/******/         modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/         // Flag the module as loaded
/******/         module.l = true;
/******/
/******/         // Return the exports of the module
/******/         return module.exports;
/******/     }
/******/
/******/
/******/     // expose the modules object (__webpack_modules__)
/******/     __webpack_require__.m = modules;
/******/
/******/     // expose the module cache
/******/     __webpack_require__.c = installedModules;
/******/
/******/     // identity function for calling harmony imports with the correct context
/******/     __webpack_require__.i = function(value) { return value; };
/******/
/******/     // define getter function for harmony exports
/******/     __webpack_require__.d = function(exports, name, getter) {
/******/         if(!__webpack_require__.o(exports, name)) {
/******/             Object.defineProperty(exports, name, {
/******/                 configurable: false,
/******/                 enumerable: true,
/******/                 get: getter
/******/             });
/******/         }
/******/     };
/******/
/******/     // getDefaultExport function for compatibility with non-harmony modules
/******/     __webpack_require__.n = function(module) {
/******/         var getter = module && module.__esModule ?
/******/             function getDefault() { return module['default']; } :
/******/             function getModuleExports() { return module; };
/******/         __webpack_require__.d(getter, 'a', getter);
/******/         return getter;
/******/     };
/******/
/******/     // Object.prototype.hasOwnProperty.call
/******/     __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/     // __webpack_public_path__
/******/     __webpack_require__.p = "";
/******/
/******/     // Load entry module and return exports
/******/     return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

window.resize = function() {
    console.info("我resize了!");
}

/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

var hello = __webpack_require__(0);
console.log(hello);

/***/ })
/******/ ]);

一大段代码看着就很捉急,不过实际上看看也不过就是个立即执行函数,我删减了一些代码,并进行了一些格式化,以下是我的代码:

(function(modules) { 
    //将我们两个文件中的代码作为一个函数对象传进这里
    //然后进行某些处理
})
(
    [ 
        (
            function(module, exports) {
                //仔细对照,这是我们被引用的hello.js的代码
                window.resize = function() {
                    console.info("我resize了!");
                }
            }
        ),
        (
            function(module, exports, __webpack_require__) {
                //仔细对照,这是我们的helloApp.js的代码,
                //只不过require被换位了__webpack_require__
                //而里面的路径'./hello.js'被换位了0,哈,简单猜想一下,这个0就是我们hello.js的代码所在的函数对象,在传进去的moudles数组中所在的索引
                var hello = __webpack_require__(0);
                console.log(hello);
            }
        ) 
    ]
);

然后我们加入部分被删掉的代码:

(function(modules) { 
            // The module cache
/******/     var installedModules = {};
/******/     // The require function
            //(2)第二步看第一步调用的这个函数,果然1就是moduleId
/******/     function __webpack_require__(moduleId) {
/******/
/******/         //  Check if module is in cache
                //  查看模块缓存中有不有moduleId为1的,有就直接返回installedModules[moduleId].exports
                //  读到这里只知道起到个缓存的作用,先不管这个是什么鬼,下一步
/******/         if(installedModules[moduleId]) {
/******/             return installedModules[moduleId].exports;
/******/         }
/******/         // Create a new module (and put it into the cache)
                // 走到这里,肯定表示没缓存嘛,于是创建下面这个对象
                // 这个对象的i为入口模块索引,
                // l是false,不知道什么鬼不管,
                // exports就是输出对象嘛,同时将这个对象的引用交给了installedModules[moduleId]和module
                // 也就是说这个对象我们缓存了
/******/         var module = installedModules[moduleId] = {
/******/             i: moduleId,
/******/             l: false,
/******/             exports: {}
/******/         };
/******/
/******/         // Execute the module function
                // 来到了有趣的地方,modules是我们传进来的模块数组,modules[moduleId]就是我们的入口函数,也就是下面这个:
                //  (
                //        function(module, exports, __webpack_require__) {
                //            hello = __webpack_require__(0);
                //            console.log(hello);
                //        }
                //    ) 
                // 那么运行下面代码的大致效果就是:
                //  var entryModule=function(module, exports, __webpack_require__) {
                //    hello = __webpack_require__(0);
                //    console.log(hello);
                //  };
                //  entryModule(module,module.exports,__webpack_require__);
                //  这段代码的就厉害了,又执行了__webpack_require__这个函数,不过此时的参数为0,也就是我们那个被引用的js的代码的函数对象的索引
/******/         modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/         // Flag the module as loaded
                // 此时我们了解到l的作用表示这个模块是否被加载
/******/         module.l = true;
/******/
/******/         // Return the exports of the module
                // 然后返回 module.exports,
                // 如果此时是hello.js的代码运行完,那么此时就会将hello.js中给形参exports的部分返回给hello那个变量
                // 此时我就明白了,webpack在不同的js之间如何建立依赖关系
                // 让被引用的部分只返回希望返回的部门,放到exports中,供引用的js调用
/******/         return module.exports;
/******/     }
/******/
/******/     // Load entry module and return exports
            // (1)第一步,看上面自带的注释,表示:这是载入入口模块,并且返回输出
            //  这个入口模块什么的,给了个s什么的,然后给了它个1,这里的s暂时看着没什么用啊
            // 那么就看成__webpack_require__(1)就好了
            // 这个1的话我们猜测就是传进来的module数组中那个引用其他js的helloApp.js的代码的函数对象的索引
/******/     return __webpack_require__(__webpack_require__.s = 1);
})
(
    [ 
        (
            function(module, exports) {
                //仔细对照,这是我们被引用的hello.js的代码
                window.resize = function() {
                    console.info("我resize了!");
                }
            }
        ),
        (
            function(module, exports, __webpack_require__) {
                //仔细对照,这是我们的helloApp.js的代码,
                //只不过require被换位了__webpack_require__
                //而里面的路径'./hello.js'被换位了0,哈,简单猜想一下,这个0就是我们hello.js的代码所在的函数对象,在传进去的moudles数组中所在的索引
                hello = __webpack_require__(0);
                console.log(hello);
            }
        ) 
    ]
);

OK,到了这里,我对webpack的大致功能就有了一个了解~~~~~。

这不就跟我们在.net或者java中的using或import一样嘛,而上面这个这个东西就是我们的Main函数,果然,没什么高大上的,其实就是这么简单。

接下来就去了解一下webpack的具体配置,首先新建一个webpack.config.js文件,然后让打包简单化:

module.exports = {
    entry: './src/app.js',
    output: {
        path: './dist',
        filename: 'app.bundle.js'
    }
};

然后直接运行webpack命令即可,就相当于自动去找webpack.config.js文件,然后根据文件中的入口app.js去生成app.bundle.js。

到这里意思就很明白了,webpack实际上就是一个类似Seajs、RequireJS一样的东西。

接下来的工作貌似就是去查webpack的如何去配置什么的了,这种细枝末节的这里就不讲了。

貌似这是一个安装的帖子 ~~~

 

  

posted on 2017-05-01 17:56  韩子卢  阅读(1872)  评论(1编辑  收藏  举报