Vue.js 2.x Development Build With Hot Reloading For External Server (using Webpack template)
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
> hello@1.0.0 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/
Vue.js 2.x Development Build With Hot Reloading For External Server (using Webpack template)的更多相关文章
- vue.js报错:Module build failed: Error: No parser and no file path given, couldn't infer a parser.
ERROR Failed to compile with 2 errors 12:00:33 error in ./src/App.vue Module build failed: Error: No ...
- Vue.js动画在项目使用的两个示例
欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 李萌,16年毕业,Web前端开发从业者,目前就职于腾讯,喜欢node.js.vue.js等技术,热爱新技术,热 ...
- vue源码分析—Vue.js 源码目录设计
Vue.js 的源码都在 src 目录下,其目录结构如下 src ├── compiler # 编译相关 ├── core # 核心代码 ├── platforms # 不同平台的支持 ├── ser ...
- Vue的理解:Vue.js新手入门指南----转
最近在逛各大网站,论坛,以及像SegmentFault等编程问答社区,发现Vue.js异常火爆,重复性的提问和内容也很多,楼主自己也趁着这个大前端的热潮,着手学习了一段时间的Vue.js,目前用它正在 ...
- Vue.js之生命周期
有时候,我们需要在实例创建过程中进行一些初始化的工作,以帮助我们完成项目中更复杂更丰富的需求开发,针对这样的需求,Vue提供给我们一系列的钩子函数. vue生命周期 beforeCreate 在实例初 ...
- Vue.js 入门指南
1.Vue.js是什么? Vue.js(读音 /vjuː/, 类似于 view) 是一套构建用户界面的 渐进式框架.与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计.Vue 的核心库只关注 ...
- vue.js选择if(条件渲染)详解
vue.js选择if(条件渲染)详解 一.总结 一句话总结: v-if <!DOCTYPE html> <html lang="en"> <head& ...
- Vue.js新手入门指南
最近在逛各大网站,论坛,以及像SegmentFault等编程问答社区,发现Vue.js异常火爆,重复性的提问和内容也很多,楼主自己也趁着这个大前端的热潮,着手学习了一段时间的Vue.js,目前用它正在 ...
- vue.js $set的使用 数组
[javascript] view plain copy <!DOCTYPE html> <html lang="en"> <head> < ...
随机推荐
- MongoDB 学习笔记(一):安装及简单shell操作
一.说明 1.该系列MongoDB学习笔记的学习环境采用的MongoDB版本为mongodb-win32-i386-2.4.6,操作系统为win7. 二.安装 1.新建两个目录,分别是D:\Insta ...
- Python3与2的故事一
print函数:(Python3中print为一个函数,必须用括号括起来:Python2中print为class) Python 2 的 print 声明已经被 print() 函数取代了,这意味着我 ...
- Xpath--使用Xpath爬取糗事百科成人版图片
#!usr/bin/env python#-*- coding:utf-8 _*-"""@author:Hurrican@file: 爬取糗事百科.py@time: 20 ...
- [luogu4107 HEOI2015] 兔子与樱花(树形dp+贪心)
传送门 Description 很久很久之前,森林里住着一群兔子.有一天,兔子们突然决定要去看樱花.兔子们所在森林里的樱花树很特殊.樱花树由n个树枝分叉点组成,编号从0到n-1,这n个分叉点由n-1个 ...
- 人脸识别中的harr特征提取(转)
影响AdaBoost人脸检测训练算法速度很重要的两方面是特征选取和特征计算.选取的特征为矩特征为Haar特征,计算的方法为积分图. (1)Haar特征: Haar特征分为三类:边缘特征.线性特 ...
- 【hdu 6342】Expression in Memories
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 把所有的问号都改成'1' 然后会发现只有+0?这种情况 需要把?改成+. 看看这样的0后面的1是不是由问号改过来的就好了.是的话 再 ...
- redis_ 5 集群
[转自 ]https://www.cnblogs.com/hjwublog/p/5681700.html#_label0 Redis集群简介 Redis 集群是3.0之后才引入的,在3.0之前,使用哨 ...
- ajax提交数据遇到400异常,原因及解决方案
开发中遇到的问题, ajax的URL写的正确但是确无法正常跳转, 开发者模式下显示请求400异常. 前后台代码如下 ------------------------------------------ ...
- POJ 2018
又一水,设dp[i]为以i结尾的有最大平均值的起始位置. #include <iostream> #include <cstdio> #include <cstring& ...
- rails new app的时候设置skip-bundle
rails new app的时候设置skip-bundle rails new app --skip-bundle 这样可以越过bundle install阶段: