某些项目使用node作为中间件,来连接前端和后端,在中间做相应处理。线上一般都是vue打包完成放入指定位置,node做配置就可访问,但这是生产时候用的。
那开发过程中,如何使用node直接启动未打包的vue项目,实现vue 和 node 一起开发呢?例子如下:
demo: https://github.com/zhangyunhou/node_start_vue
git: https://github.com/zhangyunhou/node_start_vue.git
在 build 文件夹下新建文件 dev-server.js
dev-server.js
const express = require('express');
const router = express.Router();
const webpack = require('webpack');
const webpackConfig = require('./webpack.dev.conf');
const app = express();
var compiler = webpack(webpackConfig)
//启动vue项目
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {}
})
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
// 解决history模式
app.use(require('connect-history-api-fallback')())
//启动vue项目
// serve webpack bundle output
app.use(devMiddleware)
//vue修改后自动改变
// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)
app.use((res, req, next) => {
console.log('1111111111111');
next();
});
app.listen(3000);
以上代码可以看出使用express 启动vue项目,主要使用的插件:webpack-dev-middleware webpack-hot-middleware
并做了相应配置,下面是vue主要配置文件
webpack.dev.conf.js
"use strict";
//引入node path路径模块
const path = require("path");
//引入webpack
const webpack = require("webpack");
//引入webpack开发环境配置参数
const devConfig = require("../config").dev;
//引入webpack基本配置
const baseConf = require("./webpack.base.conf");
//一个webpack配置合并模块,可简单的理解为与Object.assign()功能类似!
const merge = require("webpack-merge");
//一个创建html入口文件的webpack插件!
const HtmlWebpackPlugin = require("html-webpack-plugin");
//一个编译提示的webpack插件!
const FriendlyErrorsPlugin = require("friendly-errors-webpack-plugin");
//发送系统通知的一个node模块!
const notifier = require("node-notifier");
//将webpack基本配置与开发环境配置合并!
const devConf = merge(baseConf, {
//项目出口,webpack-dev-server 生成的包并没有写入硬盘,而是放在内存中!
output: {
//文件名
filename: "[name].js",
//html引用资源路径,在dev-server中,引用的是内存中文件!
publicPath: devConfig.publicPath
},
//生成sourceMaps(方便调试)
devtool: devConfig.devtoolType,
//
//启动一个express服务器,使我们可以在本地进行开发!!!
devServer: {
//HMR控制台log等级
clientLogLevel: "warning",
// 热加载
hot: true,
//自动刷新
inline: true,
//自动打开浏览器
open: true,
//在开发单页应用时非常有用,它依赖于HTML5 history API,如果设置为true,所有的跳转将指向index.html
historyApiFallback: true,
//主机名
host: devConfig.host,
//端口号
port: devConfig.port,
//配置反向代理解决跨域
proxy: devConfig.proxyTable,
//为你的代码进行压缩。加快开发流程和优化的作用
compress: true,
// 在浏览器上全屏显示编译的errors或warnings。
overlay: {
errors: true,
warnings: false
},
// 终端输出的只有初始启动信息。 webpack 的警告和错误是不输出到终端的
quiet: true
},
module: {
//处理模块的规则(可在此处使用不同的loader来处理模块!)
rules: [
//使用vue-loader处理以vue结尾的文件!
{
test: /\.vue$/,
loader: "vue-loader",
options: devConfig.vueloaderConf
},
//使用vue-style-loader!css-loader!postcss-loader处理以css结尾的文件!
{
test: /\.css$/,
use: [
"vue-style-loader",
{
loader: "css-loader",
options: {
sourceMap: true
}
},
{
loader: "postcss-loader",
options: {
sourceMap: true
}
}
]
},
//使用vue-style-loader!css-loader!postcss-loader处理以sass结尾的文件!
{
test: /\.scss$/,
use: [
"vue-style-loader",
{
loader: "css-loader",
options: {
sourceMap: true
}
},
{
loader: "scss-loader",
options: {
sourceMap: true
}
},
{
loader: "postcss-loader",
options: {
sourceMap: true
}
}
]
}
]
},
plugins: [
//开启HMR(热替换功能,替换更新部分,不重载页面!)
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
//显示模块相对路径
new webpack.NamedModulesPlugin(),
//编译出错时,该插件可跳过输出,确保输出资源不会包含错误!
// new webpack.NoEmitOnErrorsPlugin(),
//配置html入口信息
new HtmlWebpackPlugin({
title: "hello,xc-cli!",
filename: "index.html",
template: "index.html",
//js资源插入位置,true表示插入到body元素底部
inject: true
}),
//编译提示插件
new FriendlyErrorsPlugin({
//编译成功提示!
compilationSuccessInfo: {
messages: [
`Your application is running here: http://${devConfig.host}:${devConfig.port}`
]
},
//编译出错!
onErrors: function(severity, errors) {
if (severity !== "error") {
return;
}
const error = errors[0];
const filename = error.file.split("!").pop();
//编译出错时,右下角弹出错误提示!
notifier.notify({
title: "xc-cli",
message: severity + ": " + error.name,
subtitle: filename || "",
icon: path.join(__dirname, "xc-cli.png")
});
}
})
]
});
module.exports = devConf;
webpack.base.conf.js
"use strict";
//引入node path路径模块
const path = require("path");
//引入webpack生产环境配置参数
const prodConfig = require("../config").build;
//拼接路径
function resolve(track) {
return path.join(__dirname, "..", track);
}
//资源路径
function assetsPath(_path) {
return path.join(prodConfig.staticPath, _path);
}
//webpack 基本设置
module.exports = {
//项目入口文件->webpack从此处开始构建!
entry: ['webpack-hot-middleware/client?noInfo=true&reload=true' , path.resolve(__dirname, "../src/main.js")],
//配置模块如何被解析
resolve: {
//自动解析文件扩展名(补全文件后缀)(从左->右)
// import hello from './hello' (!hello.js? -> !hello.vue? -> !hello.json)
extensions: [".js", ".vue", ".json"],
//配置别名映射
alias: {
// import Vue from 'vue/dist/vue.esm.js'可以写成 import Vue from 'vue'
// 键后加上$,表示精准匹配!
vue$: "vue/dist/vue.esm.js",
"@": resolve("src"),
utils: resolve("src/utils"),
components: resolve("src/components"),
public: resolve("public")
}
},
module: {
//处理模块的规则(可在此处使用不同的loader来处理模块!)
rules: [
//使用babel-loader来处理src下面的所有js文件,具体babel配置在.babelrc,主要是用来转义es6
{
test: /\.js$/,
use: {
loader: "babel-loader"
},
include: resolve("src")
},
//使用url-loader(file-loader的一个再封装)对引入的图片进行编码,此处可将小于8192字节(8kb)的图片转为DataURL(base64),
//大于limit字节的会调用file-loader进行处理!
//图片一般发布后都是长缓存,故此处文件名加入hash做版本区分!
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: "url-loader",
options: {
limit: 8192,
name: assetsPath("img/[name].[hash:8].[ext]")
}
}
]
}
};
config/index.js
const _path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
//vue-loader基本配置
const baseVueLoaderConf = {
//引入postcss插件
postcss: {
config: {
path: _path.resolve("../")
}
},
//转为require调用,让webpack处理目标资源!
transformToRequire: {
video: "src",
source: "src",
img: "src",
image: "xlink:href"
}
};
//vue-loader 开发环境配置
const devVueLoaderConf = Object.assign({}, baseVueLoaderConf, {
//loaders
loaders: {
css: ["vue-style-loader", "css-loader"],
sass: ["vue-style-loader", "css-loader", "postcss-loader", "sass-loader"]
},
cssSourceMap: true
});
//vue-loader 生产环境配置
const buildVueLoaderConf = Object.assign({}, baseVueLoaderConf, {
//loaders
loaders: ExtractTextPlugin.extract({
use: ["css-loader", "postcss-loader", "sass-loader"],
fallback: "vue-style-loader"
}),
cssSourceMap: false
});
//开发/生产环境 配置参数!
module.exports = {
dev: {
publicPath: "/",
devtoolType: "cheap-module-eval-source-map",
vueloaderConf: devVueLoaderConf,
host: "localhost",
port: "3000",
autoOpenBrowser: true,
proxyTable: {}
},
build: {
publicPath: "/",
devtoolType: "source-map",
vueloaderConf: buildVueLoaderConf,
staticPath: "static"
}
};
如何启动
修改package.json 里面的dev 做如下修改
"scripts": {
"dev": "node build/dev-server.js"
},
npm run dev
或者使用 pm2 启动
pm2 start ./build/dev-server.js