Vue.js 2.x Development Build With Hot Reloading For External Server (using Webpack template)

来源:http://www.cnblogs.com/Kiddzz/archive/2017/12/19/8065743.html
-Advertisement-
Play Games

This article assuming you created your project using webpack template. vue init webpack <PROJECT_NAME> Open package.json and observe the scripts secti ...


This article assuming you created your project using webpack template.

vue init webpack <PROJECT_NAME>

Open package.json and observe the scripts section. You realize there is dev to spin up a development server with hot reload and build for production release. There isn’t an option for development release with hot reloading (watch mode).

Note: if you are not using webpack, you can use vue build index.js --watch to enable watch mode.

...
  "scripts": {
    "dev": "node build/dev-server.js",
    "start": "node build/dev-server.js",
    "build": "node build/build.js",
    "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
    "e2e": "node test/e2e/runner.js",
    "test": "npm run unit && npm run e2e",
    "lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs"
  },
...

Edit package.json to add watch.

```text
...
  "scripts": {
  	...
  	"watch": "node build/watch-build-dev.js"
  },
...

Copy build/build.js to build/watch-build-dev.js, and edit as per following (changes are commented with EDIT).

require('./check-versions')()

// EDIT: process.env.NODE_ENV = 'production'
process.env.NODE_ENV = 'development'

var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
// EDIT: var webpackConfig = require('./webpack.prod.conf')
var webpackConfig = require('./webpack.watch.conf')

// EDIT: ora('building for production...')
var spinner = ora('building for development...')
spinner.start()

rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err
  webpack(webpackConfig, function (err, stats) {
    spinner.stop()
    if (err) throw err
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }) + '\n\n')

    // EDIT: remove the following to avoid watch quit upon error
    /*
    if (stats.hasErrors()) {
      console.log(chalk.red('  Build failed with errors.\n'))
      process.exit(1)
    }
     */

    console.log(chalk.cyan('  Build complete.\n'))
    // EDIT: remove
    /*
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))
     */
  })
})

Copy build/webpack.dev.conf.js to build/webpack.watch.conf.js, and edit as per following (changes are commented with EDIT).

Update 2017-11-26: for vue-cli-template-webpack 1.2.4, copy build/webpack.prod.conf.js to build/webpack.watch.conf.js, and edit as per following (changes are commented with EDIT)

'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

// EDIT: change to development
// const env = require('../config/prod.env')
const env = require('../config/dev.env')

const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  output: {
    path: config.build.assetsRoot,
    // EDIT: remove hash
    // filename: utils.assetsPath('js/[name].[chunkhash].js'),
    // chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
    filename: utils.assetsPath('js/[name].js'),
    chunkFilename: utils.assetsPath('js/[id].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    // UglifyJs do not support ES6+, you can also use babel-minify for better treeshaking: https://github.com/babel/minify
    // EDIT: disable js minify
    /*
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
     */
    // extract css into its own file
    new ExtractTextPlugin({
      // EDIT: remove hash
      // filename: utils.assetsPath('css/[name].[contenthash].css'),
      filename: utils.assetsPath('css/[name].css'),
      // set the following option to `true` if you want to extract CSS from
      // codesplit chunks into this main css file as well.
      // This will result in *all* of your app's CSS being loaded upfront.
      // EDIT: if not then splitting vendor.css will cause javascript error
      // allChunks: false,
      allChunks: true,
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    // EDIT: disable CSS minify
    /*
    new OptimizeCSSPlugin({
      cssProcessorOptions: config.build.productionSourceMap
      ? { safe: true, map: { inline: false } }
      : { safe: true }
    }),
     */
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
      // EDIT: disable minify
      /*
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
       */
      minify: false,
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vender modules does not change
    new webpack.HashedModuleIdsPlugin(),
    // enable scope hoisting
    // EDIT:
    // new webpack.optimize.ModuleConcatenationPlugin(),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module) {
        // any required modules inside node_modules are extracted to vendor
        // EDIT
        return (
          module.resource &&
          /\.(js|css|sass|scss|less)$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    // This instance extracts shared chunks from code splitted chunks and bundles them
    // in a separate chunk, similar to the vendor chunk
    // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
    new webpack.optimize.CommonsChunkPlugin({
      name: 'app',
      async: 'vendor-async',
      children: true,
      minChunks: 3
    }),

    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ],
  // EDIT: enable watch
  watch: true,
  // EDIT: enable watch for modules
  // https://github.com/vuejs-templates/webpack/issues/378
  watchOptions: {
    aggregateTimeout: 300,
    poll: 1000
  }
})

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

Run npm run watch to enable development build in watch mode.

Note: if you include global scope CSS, remember to import them at main.js.

npm run watch
# output
> [email protected] watch /code/vue/hello
> node build/watch-build-dev.js

⠙ building for development...

 DONE  Compiled successfully in 2923ms                                5:32:25 PM

Hash: fcfe8096ae777ea47bf7
Version: webpack 2.7.0
Time: 2923ms
             Asset       Size  Chunks                    Chunk Names
            app.js     780 kB       0  [emitted]  [big]  app
static/css/app.css   93 bytes       0  [emitted]         app
        index.html  845 bytes          [emitted]         

  Build complete.

Output shall be created at dist folder. You can use symbolic link (ln -s /code/vue/hello/dist/app.js) to link to these files from you external server (e.g. nginx) development directory. You can use something like livereload on the external server development directory to reload if changes are detected.

 

original    https://code.luasoftware.com/tutorials/vuejs/vuejs-development-build-for-external-server/


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、什麼是sticky footer 在網頁設計中,Sticky footers設計是最古老和最常見的效果之一。它可以概括如下:如果頁面內容不夠長的時候,頁腳塊粘貼在視窗底部;如果內容足夠長時,頁腳塊會被內容向下推送。 二、應用場景案例 如下: 當頁面內容不夠長,比較少時,’X’關閉按鈕粘貼在視窗底 ...
  • .first level{ font size: 1.2rem; cursor: default; color: 666; } .second level{ font size: 1.1rem; padding left: 2.4rem; } .order number{ float: left; ...
  • <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="Author" content="猿道教育-Will老師" > <meta name="Keywords" content="猿說教育,HTML,CSS,JavaScri ...
  • 項目開發中,在瀏覽同事的代碼,發現他經常用一個屬性--box-sizing,很好奇是什麼,於是乎,上網查閱資料學了起來。 首先我們先複習一下盒模型的組成:一個div通常由 content(內容)+margin+padding+border組成。 瀏覽器有兩種盒模型:w3c說的標準模型和ie下的傳統模 ...
  • 1.Symbol 值通過Symbol 函數生成,凡是屬性名屬於Symbol 類型,就是 獨一無二的,可以保證不會與其他屬性名衝突。 // 沒有參數的時候 let s1 = Symbol(); let s2 = Symbol(); s1 s2; // false // 有參數的情況 let s1 = ...
  • 本文提到的HTML5僅僅指於2014年完成新一代的HTML標準。 html5主要在以下方面做了改變。 1、新增標簽 新增語義化標簽。 <header> 定義 section 或 page 的頁眉。 <nav>定義導航鏈接。 <footer> 定義 section 或 page 的頁腳 <sectio ...
  • 1. onchange事件與onpropertychange事件的區別: onchange事件在內容改變(兩次內容有可能相等)且失去焦點時觸發;onpropertychange事件是實時觸發,每增加或刪除一個字元就會觸發,通過js改變也會觸發該事件,但是該事件是IE專有。 2. oninput事件與 ...
  • 原文:https://github.com/Chalarangelo/30-seconds-of-code#anagrams-of-string-with-duplicates 作者:Chalarangelo 譯者:IT168 www.toutiao.com/i6498962961288135182 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...