幾個前端自動化工具(一)bower,grunt,gulp,jspm,karmam,webpack

前端有不少包管理工具,除了常見的webpack外還有bower,grunt,gulp,jspm,karma,這裏就蜻蜓點水的都測試一遍javascript

1 Bower https://bower.io/

使用方法:css

 

安裝bower:npm install bowerhtml

 

使用bower安裝包: install jquery --save前端

 

維護一個bower.json,格式以下:java

{
  "name": "example",
  "version": "0.0.1",
  "dependencies": {
    "jquery": "~2.1.3"
  },
  "private": true
}

 

2 GRUNT http://gruntjs.com/

安裝grunt:npm install -g grunt-clinode

 

使用grunt:直接執行gruntreact

 

維護一個gruntfile.jsjquery

module.exports = function(grunt) {
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.initConfig({
        jshint: {
            files: ['Gruntfile.js', 'src/main/javascript/*.js','src/test/javascript/*.js']
        }
    });
    grunt.registerTask('default', ['jshint']);
};
module.exports = function(grunt) {
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
            },
            build: {
                src: 'src/main/javascript/square.js',
                dest: 'build/<%= pkg.name %>.min.js'
            }
        }
    });

    // Load the plugin that provides the "uglify" task.
    grunt.loadNpmTasks('grunt-contrib-uglify');

    // Default task(s).
    grunt.registerTask('default', ['uglify']);

};

這個配置文件會吧square的js打包成一個example.jswebpack

 

grunt有不少task插件,能夠參考:http://www.gruntjs.net/pluginsgit

 

3 GULP https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md 

安裝:tnpm install -g glup

 

執行方法:gulp

 

gulpfile的格式

var gulp = require('gulp');

gulp.task('default', function() {
  console.log('gulp runs as expected');
});

表示執行的時候打印一段文字

var gulp = require('gulp'),
    uglify = require('gulp-uglify');

gulp.task('default', function () {
  gulp.src('src/main/javascript/square.js')
      .pipe(uglify())
      .pipe(gulp.dest('build'))
});

 

表示取打包一個文件

 

gulp的其餘插件列表 http://gulpjs.com/plugins/

 

4 jspm http://jspm.io/

安裝:tnpm install -g jspm

 

使用jspm安裝依賴:jspm install jquery

 

對應的config文件以下:

System.config({
  defaultJSExtensions: true,
  transpiler: "traceur",
  paths: {
    "github:*": "jspm_packages/github/*",
    "npm:*": "jspm_packages/npm/*"
  },

  map: {
    "jquery": "npm:jquery@3.1.0",
    "traceur": "github:jmcriffey/bower-traceur@0.0.88",
    "traceur-runtime": "github:jmcriffey/bower-traceur-runtime@0.0.88",
    "github:jspm/nodelibs-assert@0.1.0": {
      "assert": "npm:assert@1.4.1"
    },
    "github:jspm/nodelibs-buffer@0.1.0": {
      "buffer": "npm:buffer@3.6.0"
    },
    "github:jspm/nodelibs-process@0.1.2": {
      "process": "npm:process@0.11.5"
    },
    "github:jspm/nodelibs-util@0.1.0": {
      "util": "npm:util@0.10.3"
    },
    "github:jspm/nodelibs-vm@0.1.0": {
      "vm-browserify": "npm:vm-browserify@0.0.4"
    },
    "npm:assert@1.4.1": {
      "assert": "github:jspm/nodelibs-assert@0.1.0",
      "buffer": "github:jspm/nodelibs-buffer@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.2",
      "util": "npm:util@0.10.3"
    },
    "npm:buffer@3.6.0": {
      "base64-js": "npm:base64-js@0.0.8",
      "child_process": "github:jspm/nodelibs-child_process@0.1.0",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "ieee754": "npm:ieee754@1.1.6",
      "isarray": "npm:isarray@1.0.0",
      "process": "github:jspm/nodelibs-process@0.1.2"
    },
    "npm:inherits@2.0.1": {
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:jquery@3.1.0": {
      "process": "github:jspm/nodelibs-process@0.1.2"
    },
    "npm:process@0.11.5": {
      "assert": "github:jspm/nodelibs-assert@0.1.0",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "vm": "github:jspm/nodelibs-vm@0.1.0"
    },
    "npm:util@0.10.3": {
      "inherits": "npm:inherits@2.0.1",
      "process": "github:jspm/nodelibs-process@0.1.2"
    },
    "npm:vm-browserify@0.0.4": {
      "indexof": "npm:indexof@0.0.1"
    }
  }
});

 

5 karma https://github.com/karma-runner/karma

 

karma能夠理解成一個測試工具

 

安裝:tnpm install -g karma-cli

 

執行方法:karma start src/test/javascript/karma.conf.js

 

config文件:

module.exports = function(config) {
    config.set({
        basePath: '../../..',
        frameworks: ['jasmine'],
        files: [
            'src/main/javascript/*.js',
            'src/test/javascript/*.js'
        ],
        exclude: ['src/test/javascript/karma.conf*.js'],
        reporters: ['progress'],
        port: 9876,
        logLevel: config.LOG_INFO,
        browsers: ['PhantomJS'],
        singleRun: false,
        autoWatch: true,
        plugins: [
            'karma-jasmine',
            'karma-phantomjs-launcher'
        ]
    });
};

 

相關測試文件以下:

describe('The square function', function(){
    it('should square a number', function(){
        expect(square(3)).toBe(19);
    });
});

 

測試輸出以下:

12 07 2016 17:25:33.266:WARN [Chrome 51.0.2704 (Windows 7 0.0.0)]: Disconnected (1 times)
12 07 2016 17:25:33.572:INFO [Chrome 51.0.2704 (Windows 7 0.0.0)]: Connected on socket /#r_xSgQYtlNOJ5LSlAAAD with id man
ual-5079
PhantomJS 1.9.8 (Windows 7 0.0.0) The square function should square a number FAILED
        Expected 9 to be 19.
            at D:/test/src/test/javascript/squareSpec.js:3
Chrome 51.0.2704 (Windows 7 0.0.0) The square function should square a number FAILED
        Expected 9 to be 19.
            at Object.<anonymous> (D:/test/src/test/javascript/squareSpec.js:3:27)
PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.02 secs / 0.003 secs)
Chrome 51.0.2704 (Windows 7 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.057 secs / 0.001 secs)

配置文件其餘參數能夠參考:https://karma-runner.github.io/1.0/config/configuration-file.html

 

 

6 webpack https://github.com/webpack

 

webpack是一個模塊資源加載器,其中js,css,img均可以理解爲一個一個資源,這些都是用不一樣loader進行加載的,webpack下不一樣的loader能夠參考 http://webpack.github.io/docs/list-of-loaders.html

 

好比一個bableloader就能夠以下定義

module: {
  loaders: [
    {
      test: /\.js$/,
      exclude: /(node_modules|bower_components)/,
      loader: 'babel', // 'babel-loader' is also a legal name to reference
      query: {
        presets: ['es2015']
      }
    }
  ]
}

 

css和圖片的加載器

module: {
    loaders: [
      { test: /\.less$/, loader: 'style-loader!css-loader!less-loader' }, // use ! to chain loaders
      { test: /\.css$/, loader: 'style-loader!css-loader' },
      {test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'} // inline base64 URLs for <=8k images, direct URLs for the rest
    ]
  }

 

resolve這個配置用來解析擴展文件中的別名

 

resolve: {
  alias: {
    'oneui': path.join(__dirname, 'node_modules', '@ali/oneui'),
    'react': path.join(__dirname, 'node_modules', 'react'),
    'components': path.join(__dirname, './src/components'),
    'layouts': path.join(__dirname, './src/layouts'),
    'utils': path.join(__dirname, './src/utils'),
    'views': path.join(__dirname, './src/views'),
    'styles': path.join(__dirname, './src/styles'),
  },
  extensions: ['', '.js', '.jsx', '.scss', '.css', '.json'],
},

 

能夠用如下命令查看webpack的報錯信息

webpack --display-error-details

 

output下這個publicpath能夠用來替換cdn,能夠在靜態頁面裏直接應用對應的路徑,好比<script type="text/javascript" src="/static/vendors.js"></script>

output: {
  path: path.resolve(__dirname, 'build'),
  filename: '[name].js',
  publicPath: '/static/',
},

 

 

代碼熱替換:

 

這裏使用的是webpack-dev-server,因此啓動的時候使用webpack-dev-server --hot --quiet 這個命令便可,而後訪問呢http://localhost:8080/webpack-dev-server/ 便可獲取對應的功能

 

webpackdevserver的文檔能夠參考:http://webpack.github.io/docs/webpack-dev-server.html

 

react的熱部署

 

這裏能夠使用react-hot-loader這個神器 http://gaearon.github.io/react-hot-loader/getstarted/

 

配置加載器爲:test: /\.jsx?$/, include: [path.resolve(__dirname, 'src/main/webapp'), fs.realpathSync('./node_modules/@ali/oneui')], loaders: ['react-hot', 'babel'],

使用插件:new webpack.HotModuleReplacementPlugin(),

另外還須要更改下入口文件 entry: [ 'webpack-dev-server/client?http://0.0.0.0:3000', // WebpackDevServer host and port 'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors './scripts/index' // Your appʼs entry point ]

 

後臺開發如何加載熱部署的前臺文件

 

1 更改publicpath爲publicPath: 'http://localhost:8080/build/',

2 後端頁面引用的腳本以下就能動態加載對應的文件了

<link rel="stylesheet" href="http://localhost:8080/build/style.css"/>
<script src="http://localhost:8080/build/vendors.js"></script>
<script src="http://localhost:8080/build/app.js"></script>

3 發佈線上的時候更改參數爲--output-public-path /build/

 

整體的packagejson的發佈腳本以下

"mydaily":".\\node_modules\\\\.bin\\webpack-dev-server --config webpack.config.js --hot --inline",
"mybuild":".\\node_modules\\\\.bin\\webpack --config webpack.config.js --output-public-path /build/",
"myclean": ".\\node_modules\\\\.bin\\rimraf  .\\src\\main\\webapp\\build",

 

 

文檔參考:

http://webpack.github.io/docs/

https://github.com/petehunt/webpack-howto

http://zhaoda.net/webpack-handbook/index.html

相關文章
相關標籤/搜索