侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 130562 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

几个前端自动化工具(一)bower,grunt,gulp,jspm,karmam,webpack

2024-05-07 星期二 / 0 评论 / 0 点赞 / 50 阅读 / 10867 字

前端有很多包管理工具,除了常见的webpack外还有bower,grunt,gulp,jspm,karma,这里就走马观花的都测试一遍 1 Bowerhttps://bower.io/ 使用方法:

前端有很多包管理工具,除了常见的webpack外还有bower,grunt,gulp,jspm,karma,这里就走马观花的都测试一遍

1 Bower https://bower.io/

使用方法:

 

安装bower:npm install bower

 

使用bower安装包: install jquery --save

 

维护一个bower.json,格式如下:

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

 

2 GRUNT http://gruntjs.com/

安装grunt:npm install -g grunt-cli

 

使用grunt:直接执行grunt

 

维护一个gruntfile.js

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.js

 

grunt有很多task插件,可以参考:http://www.gruntjs.net/plugins

 

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:[email protected]",    "traceur": "github:jmcriffey/[email protected]",    "traceur-runtime": "github:jmcriffey/[email protected]",    "github:jspm/[email protected]": {      "assert": "npm:[email protected]"    },    "github:jspm/[email protected]": {      "buffer": "npm:[email protected]"    },    "github:jspm/[email protected]": {      "process": "npm:[email protected]"    },    "github:jspm/[email protected]": {      "util": "npm:[email protected]"    },    "github:jspm/[email protected]": {      "vm-browserify": "npm:[email protected]"    },    "npm:[email protected]": {      "assert": "github:jspm/[email protected]",      "buffer": "github:jspm/[email protected]",      "process": "github:jspm/[email protected]",      "util": "npm:[email protected]"    },    "npm:[email protected]": {      "base64-js": "npm:[email protected]",      "child_process": "github:jspm/[email protected]",      "fs": "github:jspm/[email protected]",      "ieee754": "npm:[email protected]",      "isarray": "npm:[email protected]",      "process": "github:jspm/[email protected]"    },    "npm:[email protected]": {      "util": "github:jspm/[email protected]"    },    "npm:[email protected]": {      "process": "github:jspm/[email protected]"    },    "npm:[email protected]": {      "assert": "github:jspm/[email protected]",      "fs": "github:jspm/[email protected]",      "vm": "github:jspm/[email protected]"    },    "npm:[email protected]": {      "inherits": "npm:[email protected]",      "process": "github:jspm/[email protected]"    },    "npm:[email protected]": {      "indexof": "npm:[email protected]"    }  }});

 

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 manual-5079PhantomJS 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:3Chrome 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

 

 

广告 广告

评论区