[front-end] 环境 本地开发

以后简书不写技术了。
搬过来
会根据每天的内容持续更新

webpack

webpack多环境配置

针对dev和prod要不同的配置

dev

  1. devtool: ‘sourcemap’ 用于在调试时能对应到对应的代码位置
  2. 开发服务器,在下一章中会具体说明,主要是用于热更新与热加载

product

  1. devtool: false 关掉map可以提高编译速度及代码量
  2. 代码压缩: 官方建议使用UglifyJsPlugin

     plugins: [
        new webpack.optimize.UglifyJsPlugin({
          sourceMap: true
        })
     ]
    

开发服务器

webpack官方给了三种本地开发方式
watch方式太简单了不说了

webpack-dev-middleware

webpack-dev-middleware为一个内建express服务器
webpack-hot-middleware为一中间层插件,用于热加载更新网页,需基于webpack-dev-middleware
http-proxy-middle作为中间proxy层转发

webpack-dev-middleware

webpack-dev-middleware不会将文件打包到真是硬盘上,而是打包到内存中,通过webpack.config.js获取到webpack文件,随后将其打包到内存中

var webpack = require('webpack')
var webpackConfig = require('./webpack.config')
var compiler = webpack(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
  // quiet: true, // quite mode won't output compile message in console
})

服务器则采用express实现

var express = require('express')
var app = express();
app.use(devMiddleware);

文件结构发生变化时会触发重编译(watch-mode下)

compiler.plugin('compilation', function (compilation) {
console.log('compilation');
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
    // do sth here, mostly hot-middleware
    cb();
  });
})

原理
// TODO
参考
在webpack-dev-middleware中无法使用chunkhash,需要在webpack.config.js中针对不同对环境配置

webpack-hot-middleware

hotmiddleware基于devmiddleware
在server配置文件中需要加上

var hotMiddleware = require('webpack-hot-middleware')(compiler, {
  log: false,
  heartbeat: 2000
})
app.use(hotMiddleware)

同时,在重新编译后要通过hotmiddleware推送

// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
  console.log('compilation')
  compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
    hotMiddleware.publish({ action: 'reload' })
    cb()
  })
})

最后,在webpack.config.dev.js中需要加上两条
entry中的app加入client

require('eventsource-polyfill'); // 这条的作用是兼容ie没有event
var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true');
hotClient.subscribe(function (event) {
  // client端,通过event事件触发,类型为reload时触发页面刷新
  if (event.action === 'reload') {
    window.location.reload();
  }
});    

plugins加上

plugins: [
  // OccurenceOrderPlugin is needed for webpack 1.x only
  new webpack.optimize.OccurenceOrderPlugin(),
  new webpack.HotModuleReplacementPlugin(),
  //   Use NoErrorsPlugin for webpack 1.x
  new webpack.NoEmitOnErrorsPlugin()
]

http-proxy-middleware

作为代理转发层
在server配置文件中加上

app.use(require('http-proxy-middleware')(
    filter,
    {
        target,
    }
));

其中filter对应需要代理的请求,target是代理转发的域名
例如

app.use(require('http-proxy-middleware')(
    '/login',
    {
        target: 'http://localhost:3000'
    }
));

会将所有的”/login”请求转发到localhost:3000下

你可能感兴趣的:(技术应用总结,front-end)