nodejs构建vue
There are so many ways we can build Vue apps and ship for production. One way is to build the Vue app with NodeJS or Java and another way is to build the Vue.js and serve that static content with the NGINX web server. With NodeJS we have to deal with the server code as well, for example, you need to load index.html page with node.
我们可以通过多种方式来构建Vue应用并交付生产。 一种方法是使用NodeJS或Java构建Vue应用程序,另一种方法是构建Vue.js并通过NGINX Web服务器提供该静态内容。 使用NodeJS,我们还必须处理服务器代码,例如,您需要使用node加载index.html页面。
In this post, we will see the details and implementation with the NodeJS. We will go through step by step with an example.
在本文中,我们将看到NodeJS的详细信息和实现。 我们将逐步举例。
Introduction
介绍
Prerequisites
先决条件
Example Project
示例项目
Just Enough NodeJS For This Project
足够用于该项目的NodeJS
Development Phase
开发阶段
How To Build Project For Production
如何建立生产项目
Summary
摘要
Conclusion
结论
介绍 (Introduction)
Vue.js is a Progressive JavaScript Framework for building web apps and it doesn’t load itself in the browser. We need some kind of mechanism that loads the index.html (single page) of Vue application with all the dependencies(CSS and js files) in the browser. In this case, we are using node as the webserver which loads Vue assets and accepts any API calls from the Vue UI app.
Vue.js是一个用于构建Web应用程序的渐进式JavaScript框架,它不会在浏览器中加载自身。 我们需要某种机制来加载Vue应用程序的index.html (单页)以及浏览器中的所有依赖项(CSS和js文件)。 在这种情况下,我们将节点用作加载Vue资产并接受来自Vue UI应用程序的所有API调用的Web服务器。
![Image for post](https://miro.medium.com/max/9999/1*EHO8wDA0qf7ganjna6s6RA.png)
If you look at the above diagram all the web requests without the /api will go to Vue routing and the Vue Router kicks in and loads components based on the path. All the paths that contain /api will be handled by the Node server itself.
如果您查看上面的图,所有不带/ api的Web请求都将转到Vue路由,Vue路由器将启动并根据路径加载组件。 包含/ api的所有路径都将由节点服务器本身处理。
In this post, we are going to develop the Vue app with NodeJS and see how to build for production.
在本文中,我们将使用NodeJS开发Vue应用程序,并了解如何为生产而构建。
先决条件 (Prerequisites)
There are some prerequisites for this article. You need to have nodejs installed on your laptop and know-how Http works. If you want to practice and run this on your laptop you need to have these on your machine.
本文有一些先决条件。 您需要在笔记本电脑上安装nodejs并了解Http的工作原理。 如果要在笔记本电脑上练习并运行此程序,则需要在计算机上安装它们。
示例项目 (Example Project)
This is a simple project which demonstrates developing and running Vue application with NodeJS. We have a simple app in which we can add users, count, and display them at the side, and retrieve them whenever you want.
这是一个简单的项目,演示了如何使用NodeJS开发和运行Vue应用程序。 我们有一个简单的应用程序,可以在其中添加用户,计数并在侧面显示它们,并在需要时检索它们。
![Image for post](https://miro.medium.com/freeze/max/9999/1*jFwMc8lwuC4BX9EUE08z6g.gif)
As you add users we are making an API call to the nodejs server to store them and get the same data from the server when we retrieve them. You can see network calls in the following video.
添加用户时,我们正在对nodejs服务器进行API调用,以存储它们并在检索用户时从服务器获取相同的数据。 您可以在以下视频中看到网络通话。
![Image for post](https://miro.medium.com/freeze/max/9999/1*N0g9MOZG4xoRyKU7Zop-wA.gif)
Here is a Github link to this project. You can clone it and run it on your machine.
这是该项目的Github链接。 您可以克隆它并在计算机上运行它。
// clone the project
git clone https://github.com/bbachi/vuejs-nodejs-example.git// strat the api
cd api
npm install
npm run dev// start the react app
cd my-app
npm install
npm run serve
就足够这个项目的NodeJS (Just Enough NodeJS For This Project)
If you are new to NodeJS don’t worry this short description is enough to get you started with this project. If you are already aware of NodeJS, you can skip this section.
如果您是NodeJS的新手,请不要担心,这段简短的说明足以让您开始使用此项目。 如果您已经知道NodeJS,则可以跳过本节。
NodeJS is an asynchronous event-driven javascript runtime environment for server-side applications. The current version of the nodejs is 12 and you can install it from this link here. You can click on any LTS link and the NodeJS package is downloaded and you can install it on your laptop.
NodeJS是用于服务器端应用程序的异步事件驱动的javascript运行时环境。 当前的nodejs版本是12 ,您可以在此链接中安装它。 您可以单击任何LTS链接,然后下载NodeJS软件包,然后将其安装在笔记本电脑上。
You can check the version of the Node with this command node -v.
You can run javascript on the node REPL by typing the command node
on the CLI.
您可以使用此命令node -v.
检查Node的版本node -v.
您可以通过在CLI上键入命令node
在节点REPL上运行javascript。
![Image for post](https://miro.medium.com/max/9999/0*kTLVgPJvzHQvrq8h.png)
The installation of a node is completed and you know how to run javascript. You can even run javascript files. For example, Let’s put the above commands in the sample.js file and run it with this command node sample.js.
节点的安装已完成,您知道如何运行javascript。 您甚至可以运行javascript文件。 例如,让我们将以上命令放入sample.js文件,并使用此命令node sample.js.
运行它node sample.js.
var x = 10;
var y = 20;
var z = x + y;
console.log(z);
开发阶段 (Development Phase)
Usually, the way you develop and the way you build and run in production are completely different. Thatswhy, I would like to define two phases: Development phase and Production phase.
通常,您的开发方式以及在生产中构建和运行的方式是完全不同的。 因此,我想定义两个阶段:开发阶段和生产阶段。
In the development phase, we run the nodejs server and the Vue app on completely different ports. It’s easier and faster to develop that way. If you look at the following diagram the Vue app is running on port 8080 with the help of a webpack dev server and the nodejs server is running on port 3080.
在开发阶段,我们在完全不同的端口上运行nodejs服务器和Vue应用程序。 这样开发起来更容易,更快捷。 如果您查看下图,则在Webpack开发服务器的帮助下Vue应用程序在端口8080上运行,而nodejs服务器在端口3080上运行。
![Image for post](https://miro.medium.com/max/9999/1*mUJz6zdND-2Q9R6zOI8Uyw.png)
项目结构 (Project Structure)
Let’s understand the project structure for this project. We will have two package.json: one for the Vue and another for nodejs API. It’s always best practice to have completely different node_modules for each one. In this way, you won’t get merging issues or any other problems regarding web and server node modules collision.
让我们了解该项目的项目结构。 我们将有两个package.json:一个用于Vue,另一个用于nodejs API。 始终最好的做法是每个节点都有完全不同的node_modules 。 这样,您将不会遇到合并问题或有关Web和服务器节点模块冲突的任何其他问题。
![Image for post](https://miro.medium.com/max/9999/1*w-karqiAaNE3MQ9aHrzhkw.png)
If you look at the above project structure, all the React app resides under the my-app folder and nodejs API resides under the api folder. If you put NodeJS API at the root folder instead of in a separate folder you might have issues with the Vue CLI picking up root node_modules.
如果您查看上述项目结构,则所有React应用程序都位于my-app文件夹下,而nodejs API则位于api文件夹下。 如果将NodeJS API放在根文件夹而不是单独的文件夹中,则Vue CLI拾取根node_modules可能会遇到问题。
NodeJS API (NodeJS API)
We use the express and nodemon on the server-side. Express is the Fast, unopinionated, minimalist web framework for NodeJS and nodemon is the library which makes your API reloads automatically whenever there is a change in the files. Let’s install these two dependencies. nodemon is only used for development so install this as a dev dependency.
我们在服务器端使用express和nodemon。 Express是用于NodeJS的快速,不受限制的,极简的Web框架,而nodemon是可让您的API在文件发生更改时自动重新加载的库。 让我们安装这两个依赖项。 nodemon仅用于开发,因此请将其安装为dev依赖项。
npm install express --save
npm install nodemon --save-dev
Here is the package.json of nodejs API.
这是nodejs API的package.json 。
{
"name": "api",
"version": "1.0.0",
"description": "example project react with nodejs",
"main": "server.js",
"scripts": {
"start": "node server.bundle.js",
"build": "webpack",
"dev": "nodemon ./server.js localhost 3080"
},
"repository": {
"type": "git",
"url": "git+https://github.com/bbachi/vuejs-nginx-docker.git"
},
"author": "Bhargav Bachina",
"license": "ISC",
"bugs": {
"url": "https://github.com/bbachi/vuejs-nginx-docker/issues"
},
"homepage": "https://github.com/bbachi/vuejs-nginx-docker#readme",
"dependencies": {
"express": "^4.17.1",
"http-proxy-middleware": "^1.0.4"
},
"devDependencies": {
"del": "^5.1.0",
"fancy-log": "^1.3.3",
"gulp": "^4.0.2",
"gulp-zip": "^5.0.1",
"nodemon": "^2.0.4",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-stream": "^5.2.1"
}
}
We need to import express and define two routes: /api/users and /api/user and the server listening on the port 3080. Here is the server.js file. We use body-parser to handle data in the http request object.
我们需要导入express并定义两个路由: / api / users和/ api / user,以及侦听端口3080的服务器。这是server.js文件。 我们使用body-parser处理http请求对象中的数据。
const express = require('express');
const path = require('path');
const app = express(),
bodyParser = require("body-parser");
port = 3080;
// place holder for the data
const users = [];
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '../my-app/build')));
app.get('/api/users', (req, res) => {
console.log('api/users called!')
res.json(users);
});
app.post('/api/user', (req, res) => {
const user = req.body.user;
console.log('Adding user:::::', user);
users.push(user);
res.json("user addedd");
});
app.get('/', (req,res) => {
res.sendFile(path.join(__dirname, '../my-app/build/index.html'));
});
app.listen(port, () => {
console.log(`Server listening on the port::${port}`);
});
You need to start the nodejs API with this command npm run dev
and the moment you change any file, it will be automatically updated. We are using nodemon to watch files.
您需要使用此命令npm run dev
启动nodejs API,更改任何文件后,该文件将自动更新。 我们正在使用nodemon来监视文件。
![Image for post](https://miro.medium.com/freeze/max/9999/1*ewK7uKxmydq62sdb5uwHbQ.gif)
Vue用户界面 (Vue UI)
Now the nodejs API is running on port 3080. Now it’s time to look at the Vue UI. The entire Vue app is under the folder my-app. You can create with this command vue create my-app
I am not going to put all the files here you can look at the entire files in the above Github link or here.
现在,nodejs API在端口3080上运行。现在是时候查看Vue UI了。 整个Vue应用程序位于my-app文件夹下。 您可以使用此命令vue create my-app
我不会将所有文件放在此处,您可以在上面的Github链接中或此处查看整个文件。
Let’s see some important files here. Here is the service file which calls node API. This is a service file with two async functions that use fetch API to make the API calls.
让我们在这里看到一些重要的文件。 这是调用节点API的服务文件。 这是一个具有两个异步函数的服务文件,这些函数使用访存API进行API调用。
export async function getAllUsers() {
const response = await fetch('/api/users');
return await response.json();
}
export async function createUser(data) {
const response = await fetch(`/api/user`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({user: data})
})
return await response.json();
}
Here is the Dashboard component that calls this service and gets the data from the API. Once we get the data from the API we set the state accordingly and renders the appropriate components again to pass the data down the component tree. You can find other components here.
这是调用此服务并从API获取数据的仪表板组件。 从API获取数据后,我们将相应地设置状态,并再次渲染适当的组件以将数据传递到组件树。 您可以在这里找到其他组件。
<template>
<div class="hello">
<Header />
<div class="container mrgnbtm">
<div class="row">
<div class="col-md-8">
<CreateUser @createUser="userCreate($event)" />
</div>
<div class="col-md-4">
<DisplayBoard :numberOfUsers="numberOfUsers" @getAllUsers="getAllUsers()" />
</div>
</div>
</div>
<div class="row mrgnbtm">
<Users v-if="users.length > 0" :users="users" />
</div>
</div>
</template>
<script>
import Header from './Header.vue'
import CreateUser from './CreateUser.vue'
import DisplayBoard from './DisplayBoard.vue'
import Users from './Users.vue'
import { getAllUsers, createUser } from '../services/UserService'
export default {
name: 'Dashboard',
components: {
Header,
CreateUser,
DisplayBoard,
Users
},
data() {
return {
users: [],
numberOfUsers: 0
}
},
methods: {
getAllUsers() {
getAllUsers().then(response => {
console.log(response)
this.users = response
this.numberOfUsers = this.users.length
})
},
userCreate(data) {
console.log('data:::', data)
createUser(data).then(response => {
console.log(response);
this.getAllUsers();
});
}
},
mounted () {
this.getAllUsers();
}
}
</script>
Vue UI和Node API之间的交互 (Interaction between Vue UI and Node API)
In the development phase, the Vue app is running on port 8080 with the help of a Vue CLI and nodejs API running on port 3080.
在开发阶段,借助于在端口3080上运行的Vue CLI和nodejs API,Vue应用程序将在端口8080上运行。
There should be some interaction between these two. We can proxy all the API calls to nodejs API. Vue CLI provides some inbuilt functionality and to tell the development server to proxy any unknown requests to your API server in development, we just need to add this file at the root where package.json resides and configures the appropriate API paths.
两者之间应该有一些互动。 我们可以将所有API调用代理到nodejs API。 Vue CLI提供了一些内置功能,并告诉开发服务器将任何未知请求代理到开发中的API服务器,我们只需要将此文件添加到package.json所在的根目录并配置适当的API路径即可。
module.exports = {
devServer: {
proxy: {
'^/api': {
target: 'http://localhost:3080',
changeOrigin: true
},
}
}
}
With this in place, all the calls start with /api will be redirected to http://localhost:3080 where the nodejs API running.
有了这个,所有以/ api开头的调用将被重定向到http:// localhost:3080 运行nodejs API的位置。
Once this is configured, you can run the Vue app on port 8080 and nodejs API on 3080 still make them work together.
配置完成后,您可以在端口8080上运行Vue应用程序,而在3080上的nodejs API仍然可以使它们协同工作。
// nodejs API (Terminal 1)cd api (change it to API directory)
npm run dev// React app (Terminal 2)cd my-app (change it to app directory)
npm run serve
如何建立生产项目 (How To Build Project For Production)
The Vue app runs on the port 3000 with the help of a Vue CLI. This is not the case for running in production. We have to build the Vue project and load those static assets with the node server. Let’s see those step by step here.
Vue应用程序借助Vue CLI在端口3000上运行。 在生产中运行不是这种情况。 我们必须构建Vue项目,并将这些静态资产加载到节点服务器。 让我们逐步了解这些内容。
First, we need to build the Vue project with this command npm run build
or vue-cli-service build
and all the built assets will be put under the dist folder.
首先,我们需要使用此命令npm run build
或vue-cli-service build
来构建Vue项目,所有构建的资产都将放在dist文件夹下。
![Image for post](https://miro.medium.com/max/9999/1*coaWee85h76JJa1n8N3u9A.png)
Second, we need to make some changes on the server-side. Here is the modified server.js file.
其次,我们需要在服务器端进行一些更改。 这是修改后的server.js文件。
We need to import path that resolves
.
and..
, and uses the appropriate file separator for any platform我们需要导入解决的路径
.
和..
,并为任何平台使用适当的文件分隔符We have to use express.static at line number 11 to let express know there are a dist folder and assets of the Vue build.
我们必须在第11行使用express.static来使express知道Vue构建中有一个dist文件夹和资产。
Load index.html for the default route / at line number 26
加载index.html作为默认路由/在第26行
const express = require('express');
const path = require('path');
const randomId = require('random-id');
const app = express(),
bodyParser = require("body-parser");
port = 3080;
// place holder for the data
const users = [];
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '../my-app/dist')));
app.get('/api/users', (req, res) => {
console.log('api/users called!!!!!!!')
res.json(users);
});
app.post('/api/user', (req, res) => {
const user = req.body.user;
user.id = randomId(10);
console.log('Adding user:::::', user);
users.push(user);
res.json("user addedd");
});
app.get('/', (req,res) => {
res.sendFile(path.join(__dirname, '../my-app/build/index.html'));
});
app.listen(port, () => {
console.log(`Server listening on the port::${port}`);
});
Once you are done with the above changes, you can actually run the whole app with the nodejs server running on port 3080 like below as nodejs acts as a web server as well. At this time you don’t need to run Vue CLI on port 8080. Every time you change anything on the Vue side you need to build the project again to reflect the changes.
完成上述更改后,您实际上可以使用运行在端口3080上的nodejs服务器运行整个应用程序,如下所示,因为nodejs也可以充当Web服务器。 目前,您不需要在端口8080上运行Vue CLI 。每次在Vue端进行任何更改时,都需要再次构建项目以反映所做的更改。
![Image for post](https://miro.medium.com/max/9999/1*LlhsRIMyeMsUZ65gKpblvg.png)
摘要 (Summary)
- There are so many ways we can build Vue apps and ship for production. 我们可以通过多种方式来构建Vue应用并交付生产。
- One way is to build the Vue app with NodeJS. 一种方法是使用NodeJS构建Vue应用。
- In the development phase, we can run Vue UI and Nodejs on separate ports. 在开发阶段,我们可以在单独的端口上运行Vue UI和Nodejs。
- The interaction between these two happens with proxying all the calls to API. 这两者之间的交互是通过代理所有对API的调用而发生的。
- In the production phase, you can build the Vue app and put all the assets in the build folder and load it with the node server. 在生产阶段,您可以构建Vue应用并将所有资产放置在build文件夹中,然后将其与节点服务器一起加载。
- Nodejs act as a web server as well in the above case. You need to let express know where are all the Vue build assets are. 在上述情况下,Node.js也充当Web服务器。 您需要让express知道所有Vue构建资产在哪里。
- We can package the application in a number of ways. 我们可以通过多种方式打包应用程序。
- You can deploy the packaged zip folder in any node environment. 您可以在任何节点环境中部署打包的zip文件夹。
结论 (Conclusion)
This is one way of building and shipping Vue apps. This is really useful when you want to do server-side rendering or you need to do some processing. NodeJS is non-blocking IO and it is very good for normal websites as well. In future posts, I will discuss more on deploying strategies for this kind of architecture.
这是构建和交付Vue应用程序的一种方法。 当您要执行服务器端渲染或需要进行一些处理时,这非常有用。 NodeJS是非阻塞IO,对于普通网站也非常有用。 在以后的文章中,我将讨论有关这种架构的部署策略的更多信息。
nodejs构建vue