一步步構造自己的vue2.0+webpack環境

SharonTucke 8年前發布 | 265K 次閱讀 Vue.js Vue.js開發 webpack

前面vue2.0和webpack都已經有接觸了些(vue.js入門, webpack入門之簡單例子跑起來 ),現在開始學習如何構造自己的vue2.0+webpack環境。

1.首先新建一個目錄vue-wkdemo,這是我們的項目目錄。執行 npm init 命令生成package.json文件。執行npm init之后,會提示你填寫一些項目的信息,一直回車默認就好了,或者直接執行 npm init -y 直接跳過詢問步驟。

2.安裝項目依賴項

npm install webpack webpack-dev-server vue-loader vue-html-loader css-loader vue-style-loader
vue-hot-reload-api babel-loader babel-core babel-plugin-transform-runtime babel-preset-es2015 babel-runtime@5 --save-dev
npm install html-webpack-plugin --save-dev
npm install vue --save

3.新建入口文件index.js,文件位置放置為:vue-wkdemo->app->index->index.js

import Vue from 'Vue'
import Favlist from './components/Favlist.vue'
Vue.config.debug = true;//開啟錯誤提示
window.onload = function () {
  new Vue({
      el: '#app',
      components: {
        'my-component': Favlist
      }
  });
}

4.構建index.html模版,文件位置放置為:vue-wkdemo->app->index->index.html

<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <title>首頁</title>
    </head>
    <body>
      <div id="app">

        <my-component></my-component>
      </div>
    </body>
</html>

5.構建vue組件Favlist.vue ,文件放置為:vue-wkdemo->app->components->Favlist.vue

<template id="template-home">
  <div>
    <div v-for="n in 10">div</div>
  </div>
</template>


<style>
body {
    color: red;
}
</style>

6.構建 webpack.config.js ,文件放置為:vue-wkdemo->build->webpack.config.js

// nodejs 中的path模塊
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // 入口文件,path.resolve()方法,可以結合我們給定的兩個參數最后生成絕對路徑,最終指向的就是我們的index.js文件
    entry: path.resolve(__dirname, '../app/index/index.js'),
    // 輸出配置
    output: {
        // 輸出路徑是 myProject/output/static
        path: path.resolve(__dirname, '../output/static'),
        publicPath: 'static/',
        filename: '[name].[hash].js',
        chunkFilename: '[id].[chunkhash].js'
    },
    resolve: {
        extensions: ['', '.js', '.vue'],
        alias: {
            'Vue': 'vue/dist/vue.js'
        }
    },
    module: {

        loaders: [
            // 使用vue-loader 加載 .vue 結尾的文件
            {
                test: /\.vue$/,
                loader: 'vue'
            },
            {
                test: /\.js$/,
                loader: 'babel?presets=es2015',
                exclude: /node_modules/
            }
        ]
    },
    Favlist: {
        loaders: {
            js: 'babel'
        }
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: '../index.html',
            template: path.resolve(__dirname, '../app/index/index.html'),
            inject: true
        })
    ]
}

View Code

7.運行構建命令 : ‘webpack –display-modules –display-chunks –config build/webpack.config.js’

可以看到輸出文件:

8.到這里,我們的目錄結構為:

運行output->static->index.html這個文件,過程中遇到各種各樣的坑 (省略幾百字。。。)

最后終于看到結果了!!!

9.問題來了,每次都需要運行構建命令才能查看改變后的代碼效果,這是很沒有效率 ,于是還需要安裝  webpack-dev-middleware 中間件和 webpack-hot-middleware 中間件

npm install webpack-dev-middleware webpack-hot-middleware --save-dev

另外還需要安裝express

npm install express --save-dev

介紹下 webpack-dev-middleware 中間件,它是對webpack一個簡單的包裝,它可以通過連接服務器服務那些從webpack發射出來的文件,它有一下幾點好處:

1、不會向硬盤寫文件,而是在內存中,注意我們構建項目實際就是向硬盤寫文件。

2、當文件改變的時候,這個中間件不會再服務舊的包,你可以直接刷新瀏覽器就能看到最新的效果,這樣你就不必等待構建的時間,所見即所得。

在build目錄中創建一個dev-server.js文件,并寫入內容:

// 引入必要的模塊
var express = require('express')
var webpack = require('webpack')
var config = require('./webpack.config')

// 創建一個express實例
var app = express()

// 調用webpack并把配置傳遞過去
var compiler = webpack(config)

// 使用 webpack-dev-middleware 中間件
var devMiddleware = require('webpack-dev-middleware')(compiler, {
    publicPath: config.output.publicPath,
    stats: {
        colors: true,
        chunks: false
    }
})

// 注冊中間件
app.use(devMiddleware)

// 監聽 8888端口,開啟服務器
app.listen(8888, function (err) {
    if (err) {
        console.log(err)
        return
    }
    console.log('Listening at http://localhost:8888')
})

View Code

然后我們修改 webpack.config.js 配置文件

① 將 config.output.publicPath 修改為 ‘/‘:

// 輸出配置
    output: {
        // 輸出路徑是 myProject/output/static
        path: path.resolve(__dirname, '../output/static'),
        publicPath: '/',
        filename: '[name].[hash].js',
        chunkFilename: '[id].[chunkhash].js'
    },

② 將 plugins 中 HtmlWebpackPlugin 中的 filename 修改為 ‘app/index/index.html’

 plugins: [
        new HtmlWebpackPlugin({
            filename: 'app/index/index.html',
            template: path.resolve(__dirname, '../app/index/index.html'),
            inject: true
        })
    ]

此時,我們在項目根目錄運行下面的命令,開啟服務:

node build/dev-server.js

在瀏覽器中輸入 http://localhost:8888/app/index/index.html,如果成功了將和前面本地運行output->static->index.html這個文件的結果是一樣一樣的

不信?

為了不去修改webpack.config.js,在build目錄下新建一個webpack.dev.conf.js文件,意思是開發模式下要讀取的配置文件,并寫入一下內容:

var HtmlWebpackPlugin = require('html-webpack-plugin')
var path = require('path');
// 引入基本配置
var config = require('./webpack.config');

config.output.publicPath = '/';

config.plugins = [
    new HtmlWebpackPlugin({
        filename: 'app/index/index.html',
        template: path.resolve(__dirname, '../app/index/index.html'),
        inject: true
    })
];

module.exports = config;

View Code

這樣在dev環境下的配置文件覆蓋了基本配置文件,只需要在dev-server.js中將

var config = require('./webpack.config')

改為:

var config = require('./webpack.dev.conf')

到這里,我們已經使用webpack-dev-middleware 搭建基本的開發環境了,但是每次修改代碼后,還是需要我們手動刷新瀏覽器,接下來介紹熱加載(所謂的熱加載,意思就是說能夠追蹤我們代碼的變化,并自動更新界面,甚至還能保留程序狀態。),我們需要 webpack-hot-middleware 中間件來完成熱加載。

配合 webpack-dev-middleware 使用,我們還需要做的是:

第一步:安裝(上面我們已經安裝過)

npm install webpack-dev-middleware --save-dev

第二步:在 webpack.dev.conf.js 配置文件中添加三個插件,如下:

var HtmlWebpackPlugin = require('html-webpack-plugin')
var path = require('path');
var webpack = require('webpack');
// 引入基本配置
var config = require('./webpack.config');

config.output.publicPath = '/';

config.plugins = [
    // 添加三個插件
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),

    new HtmlWebpackPlugin({
        filename: 'app/index/index.html',
        template: path.resolve(__dirname, '../app/index/index.html'),
        inject: true
    })
];

module.exports = config;

第三步:在 webpack.config.js 文件中入口配置中添加 ‘webpack-hot-middleware/client’,如下:

entry: ['webpack-hot-middleware/client', path.resolve(__dirname, '../app/index/index.js')],

第四步:在 dev-server.js 文件中使用插件

// 引入必要的模塊
var express = require('express')
var webpack = require('webpack')
var config = require('./webpack.dev.conf')

// 創建一個express實例
var app = express()

// 調用webpack并把配置傳遞過去
var compiler = webpack(config)

// 使用 webpack-dev-middleware 中間件
var devMiddleware = require('webpack-dev-middleware')(compiler, {
    publicPath: config.output.publicPath,
    stats: {
        colors: true,
        chunks: false
    }
})

// 使用 webpack-hot-middleware 中間件
var hotMiddleware = require('webpack-hot-middleware')(compiler)

// 注冊中間件
app.use(devMiddleware)
// 注冊中間件
app.use(hotMiddleware)

// 監聽 8888端口,開啟服務器
app.listen(8888, function (err) {
    if (err) {
        console.log(err)
        return
    }
    console.log('Listening at http://localhost:8888')
})

現在重啟的服務,然后修改 Favlist.vue 中的頁面顏色為 ‘black’:

<style>
  body {
      color: black;
  }
</style>

一保存就可以看到修改后的效果,不需要手動刷新瀏覽器啦啦啦~\(≧▽≦)/~啦啦啦。

剛剛修改了webpack.config.js這個基本配置文件中的入口配置,為了不修改這個基本配置文件,我們在webpack.dev.conf.js文件中需要改下配置:

var HtmlWebpackPlugin = require('html-webpack-plugin')
var path = require('path');
var webpack = require('webpack');
// 引入基本配置
var config = require('./webpack.config');

config.output.publicPath = '/';

config.plugins = [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new HtmlWebpackPlugin({
        filename: 'app/index/index.html',
        template: path.resolve(__dirname, '../app/index/index.html'),
        inject: true
    })
];

// 動態向入口配置中注入 webpack-hot-middleware/client
var devClient = 'webpack-hot-middleware/client';
Object.keys(config.entry).forEach(function (name, i) {
    var extras = [devClient]
    config.entry[name] = extras.concat(config.entry[name])
})

module.exports = config;

View Code

然后將 webpack.config.js 文件中的入口配置修改為以下配置方式:

entry: {
        index: [
            path.resolve(__dirname, '../app/index/index.js')
        ]
    },

重啟服務,修改 Favlist.vue 中的背景色,再次查看瀏覽器,發現可以熱加載。到這里還沒結束,這里只是監聽到Favlist.vue文件的改動,為了能監聽到index.html文件的改動,我們還需要做一些工作。

第一步:在dev-server.js文件中監聽html文件改變事件,修改后的dev-server.js文件如下:

// 引入必要的模塊
var express = require('express')
var webpack = require('webpack')
var config = require('./webpack.dev.conf')

// 創建一個express實例
var app = express()

// 調用webpack并把配置傳遞過去
var compiler = webpack(config)

// 使用 webpack-dev-middleware 中間件
var devMiddleware = require('webpack-dev-middleware')(compiler, {
    publicPath: config.output.publicPath,
    stats: {
        colors: true,
        chunks: false
    }
})

var hotMiddleware = require('webpack-hot-middleware')(compiler)

// webpack插件,監聽html文件改變事件
compiler.plugin('compilation', function (compilation) {
    compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
        // 發布事件
        hotMiddleware.publish({ action: 'reload' })
        cb()
    })
})

// 注冊中間件
app.use(devMiddleware)
// 注冊中間件
app.use(hotMiddleware)

// 監聽 8888端口,開啟服務器
app.listen(8888, function (err) {
    if (err) {
        console.log(err)
        return
    }
    console.log('Listening at http://localhost:8888')
})

View Code

第二步:修改webpack.dev.conf.js文件

var HtmlWebpackPlugin = require('html-webpack-plugin')
var path = require('path');
var webpack = require('webpack');
// 引入基本配置
var config = require('./webpack.config');

config.output.publicPath = '/';

config.plugins = [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new HtmlWebpackPlugin({
        filename: 'app/index/index.html',
        template: path.resolve(__dirname, '../app/index/index.html'),
        inject: true
    })
];

// 動態向入口配置中注入 webpack-hot-middleware/client
// var devClient = 'webpack-hot-middleware/client';
var devClient = './build/dev-client';
Object.keys(config.entry).forEach(function (name, i) {
    var extras = [devClient]
    config.entry[name] = extras.concat(config.entry[name])
})

module.exports = config;

View Code

文件中修改了devClient變量,將 ‘webpack-hot-middleware/client’ 替換成 ‘./build/dev-client’,最終會導致,我們入口配置會變成下面這樣:

   entry: {
        index: [
            './build/dev-client',
            path.resolve(__dirname, '../app/index/index.js')
        ]
    },

第三步:新建build/dev-client.js文件,并編輯如下內容:

var hotClient = require('webpack-hot-middleware/client')

// 訂閱事件,當 event.action === 'reload' 時執行頁面刷新
hotClient.subscribe(function (event) {
    if (event.action === 'reload') {
        window.location.reload()
    }
})

這里我們除了引入 ‘webpack-hot-middleware/client’ 之外訂閱了一個事件,當 event.action === ‘reload’ 時觸發,而在 dev-server.js 中有發布的事件:

// webpack插件,監聽html文件改變事件
compiler.plugin('compilation', function (compilation) {
    compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
        // 發布事件
        hotMiddleware.publish({ action: 'reload' })
        cb()
    })
})

這樣,當我們的html文件改變后,就可以監聽的到,最終會執行頁面刷新,而不需要我們手動刷新。看下效果:

至此,開發環境終于搞定了。

 

 

來自:http://www.cnblogs.com/wj204/p/6031435.html

 

 本文由用戶 SharonTucke 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!