首页 > 代码库 > webpack 与 热编译webpack-dev-server

webpack 与 热编译webpack-dev-server

为啥我发现每次搭建热编译的情况都不同,但这次应该算是最科学的方式了。

  

webpack.config.js 只需要注意加大加粗的地方。这是核心,其他地方只是为了演示实战环境而已

var webpack = require("webpack");
var HtmlWebpackPlugin = require(‘html-webpack-plugin‘);

module.exports = {
    entry:{
        jq  : [                
               __dirname + ‘/src/js/jq/jquery-1.9.1.js‘,               
               __dirname + ‘/src/js/jq/jquery.uriAnchor-1.1.3.js‘    
              ],      
        app : [
               __dirname + ‘/src/js/spa.js‘,
               __dirname + ‘/src/js/spa.shell.js‘,
               __dirname + ‘/src/js/spa.util.js‘,
               __dirname + ‘/src/js/spa.chat.js‘,
               __dirname + ‘/src/js/spa.model.js‘,
               ‘webpack-dev-server/client?http://127.0.0.1:8896‘       
              ]        
    },
    output:{
        publicPath : "http://127.0.0.1:8896/",
        path       : __dirname + ‘/build/js‘,
        filename   : ‘[name].js‘
    },
    resolve: {
        alias: {
            css: __dirname + ‘/src/css/‘
        }
    },
    module : {
        loaders : [
           {test:/\.(eot|woff|woff2|svg|ttf)([\?]?.*)$/,loader:"file" },
           {test: /\.css$/,loader: ‘style-loader!css-loader‘},
           {test: /\.(png|jpe?g|gif|svg)(\?\S*)?$/,loader: ‘file-loader‘,query: {name: ‘[name].[ext]?[hash]‘}}
        ]
    },
    plugins:[
         new HtmlWebpackPlugin({
             // filename : __dirname + "/build/spa.html",//用户后台首页
             filename : "spa.html", // 配合热编译故意这样编写,这样才可以访问localhost:port/spa.html
            template : __dirname + ‘/src/spa.html‘,//模板文件
            inject   : ‘head‘,
            hash     : true,
             chunks   : ["jq","app",‘common‘]
         }),
         //提取出公共的代码
        new webpack.optimize.CommonsChunkPlugin({
            name:"common",  
            chunks:["jq","app"]
        })
    ]
}

 

package.json 同样只需要注意加粗加大的地方

{
  "name": "test_spa",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --host 127.0.0.1  --port 8896"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/dragon8github/spa.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/dragon8github/spa/issues"
  },
  "homepage": "https://github.com/dragon8github/spa#readme",
  "devDependencies": {
    "babel-cli": "^6.23.0",
    "babel-loader": "^6.3.1",
    "babel-preset-es2015": "^6.22.0",
    "css-loader": "^0.26.1",
    "html-webpack-plugin": "^2.28.0",
    "jquery": "^1.9.1",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.3.0"
  }
}

 

命令行执行 npm run dev 测试

webpack 与 热编译webpack-dev-server