See how to build an Express + Vue development environment from scratch

pre-presence presence The processing tool is divided into JS Preprocessing Tools and CSS Preprocessors. JavaScript has always been the most ill-lack of illness, and all JS code files will share the same namespace after being introduced by the HTML page. So there have only various “standards” try to solve this problem, but they are not native, need additional tools for special processing. Although ES6 finally introduces the module mechanism, it is not enough to “uselessly with the use of now” with the current browser support. Therefore, the most important task of JS Preprocessing Tools is to help solve the problem of JS. The CSS preprocessing tool is well understood, which is to translate Sass, Less or Stylus code, incorporate into CSS code.

The resource management tool is to help us manage the various resource files required for front-end (such as CSS, JS, Pictures, Fonts, etc.) for easy reference. Currently used solutions are to encode them directly into the JS code, and then reference them like reference to JS modules. This can be more convenient than handwriting a variety of URLs.

As the title says, we will use WebPack because it has all the features mentioned above. In addition, you also support code heat replacement, so that you don’t have to refresh the page after modifying the code, you can see the effect in your browser.

2. Select the appropriate pretreatment tool 详解如何从零开始搭建Express+Vue开发环境

of the rear end is a JS code. No need for resource management tools like front-end, in addition, Node forces you to use at least one module management scheme (CommonJS or ES6 IMPORT), and does not need to consider the dependence of code. So the backend should be simple, the only thing that needs to be considered, so how to translate ES6 into ES5 (if you plan to use ES6)if). The current common practice is to use Babel, you can use the Babel command line tool to independent compilation process, or configure Babel Register to dynamically translate when the code is running, which is undoubtedly the most convenient for development scenarios. So we choose the latter way.

3. Select the appropriate process control tool

The flow control tool is to help us manage, such as code check, compile, compression, movement, To deploy these tasks, we have made through the way you write (or a high-level write script). After the process control tool, you can complete the configuration file and a small amount of code.

The most popular solution is GULP. However, since we have to build a development environment, there is no need for mobile code, compression, deployment, etc., there is no need for powerful GULP. We only need to use Nodemon on this tool to listen to code changes and then restart Server is enough.


1. Rapid construction using Express Scaffolding Use the Scaffolding Generator provided by Express Application Generator to build the most basic application within 1s.
If you haven’t tried it before, first perform the following command to install

npm install express-generator -g

The following command generates code, and some parameters need to be entered during the execution of the command.
After completion of the fileSuch a configuration is

.├── app.js├── bin│ └── www├── package.json├── public│ ├── images │ ├── javascripts│ └── stylesheets│ └── style.css├── routes│ ├── index.js│ └── users.js└── views ├── error.jade ├── index. jade └── layout.jade
However, this structure is only back-end code file, want to combine front-end code, requires some modifications. We plan to eventually file structure should look like this

.├── src│ ├── client│ └── server└── …
it is necessary to the auto-generated code into the above-Express / src / server / path.
then we do not need to delete some things and add some things missing.

First, since we plan to use in the front frame Vue, Vue-Router management by the majority of the route, retaining only a small amount of back-end Express RESTful API routing, back-end routing settings do not need so complex, so routes contents of a folder can be simplified into a routers.js file.
Then, we need to configure Babel register, so it is necessary to add two files in the project with the path
 .babelrc  and  index.js 
, the contents are as follows:
/. babelrc

{“Presets”: [“ES2015”],}

.babelrc is the file required for Babel 6.0 /. Index.js

Require (‘Babel-register’) Require (‘./ src / server’)
   The above two sentences are completed by BEBEL registration, which climbs all 
Require or

depending on the module and translates them into ES5.

There is a WWW file in the automatically generated code. He is an EXPRESS application entry file, we put it under the Server path and renamed it is index.js so that the Babel Register configured above can find it correctly.

Why is it index.js that is renamed? This is because
Require (‘./ src / server’) go to ./src/server/index.js in the default, if you want to use other names, then remember Babel Register The configuration file is changed to
 Require (./ src /  . 
Now the rear end is temporarily annihilated, then look at the front end.

2. Rapid construction of Vue Scaffolding Similarly, the Template tool with Vue itself is recommended to generate basic code within 1s.

Although the backend of the code generated by this tool is based on Express, the code structure of the rear end portion is too simple, not suitable for subsequent development. So recommendedHere first puts the code generated by the VUE in another place, then move to the code folder generated by Express in an Express on demand.

then execute the command Generate code. You need to enter some parameters during command

 The generated code structure is like this.   
.├ – BUILD│ ├── DEV-Server.js # development Server Script│ ├── Karma.conf.js # Unit Testing config│ ├ – WebPack.Base.conf.js # Shared Base Webpack config│ ├─- # development Webpack config│ ├─- WebPack.Prod.conf.js # production WebPack config│ └── … ├── SRC│ ├─ Main.js # App Entry File│ ├─App.Vue # Main App Company│ ├─ Components # UI Components│ │ └── … │ └── Assets # module assets (Processed by Webpack) │└── … ├─ static # pure static assets (Directly Copied) ├─- Dist # Built Files Ready for Deploy ├ – Test│ └── Unit # Unit Tests│ ├─ 中… ─ Entry File│ └── … ├─.babelrc # babel config ─- .eslintrc.js # eslint config ── index.html # main html file└ – Package.json # Build Scripts and dependencies

We found there to be one. Babelrc, the content is basically the same as before, and you can ignore it. In addition, it also provides .eslintrc.js, is to match the ESLINT to check the code in line with specifications. The content in this is very simple. If you want to be lazy, you will take it directly. I feel that the custom rules are not very configured with their habits.
Then see the build path related to the build path, because we are to build a development environment, so you can pick the webpack.base.conf.js and It is recommended to merge the content into a WebPack.conf.js file, place it in the root of the project.
 After , basically, move the src directory to the / src / client created by Express, I habits all the entry files of all JSs to INDEX.JS, so hereYou can rename SRC / Client / Main.js as src / client / index.js.   Other documents are neglected first. 
The code of the front end portion is basically finished.

3. Configure WebPack

 We plan to make WebPack pack the front-end file into a build.js file, then put it in / src / server / public / JavaScripts are used in Jade templates in JavaScripts. So set the path part of WebPack (other reserved is good):   
{… Entry: path.join (__ dirname, ‘src / client / index .js’), Output: {path: path.join (__ DIRNAME, ‘SRC / Server / Public / JavaScripts /’), PublicPath: ‘/ javascripts /’, filename: ‘build.js’}, …}

As for how to start WebPack, you can choose to run it separately with a shell window, or provide proxy in the form of an Express middleware. In the latter manner, WebPack does not generate the packaged code on the disk, but retains in memory. We have selected a way because it is more convenient.

Web should only be deployed in the development environment in the form of Express middleware, so you need to modify /src/server/index.js, the key is to increase these sentences

Import Webpack from ‘WebPack’Import webpackDevMiddleware from’ webpack-dev-middleware’import webpackHotMiddleware from ‘webpack-hot-middleware’import config from’ ../../webpack.config’const compiler = webpack (config) app.use (webpackDevMiddleware (compiler, {publicPath: config.output.publicPath, Stats: {colors: true},}) App.use (WebPackhotmiddleWare (Compiler))

After each starting express The webpack middleware will intercept the request for the config.output.publicPath address and return the correct result, and if there is a change in the file listened by the WebPack, it will immediately notify the front end to generate a corresponding change.

4. Configure NodeMon

before, it is planned to start Server with NodeMon and listen to code changes. NodeMon will monitor all JS code except .git and node_modules paths, Node, because we already have a WebPack listening front-end code, so you have to do related configuration to let Nodemon only listen to a piece of code.
  Added file nodemon.json under the project root path, the content is  

{“Verbose”: true, “ignore”: [“SRC / Server / public / “],” e”: {” restart “:” Osascript -e ‘display notification \ “app restarted due to: \ n’ $ filename ‘\” with title \ “nodemon \”‘ “},” watch “: [” SRC / Server / “],” eNV “: {” name_env “:” develop “},” ext “:” js jade “}

, where Verbose is set to True Print more rich log information, which is very helpful to development.

We choose to let Nodemon monitor SRC / Server / Directory and ignore the SRC / Server / Public Directory, because there is a front-end WebPack generated a package. Note We use WebPack in the form of Express middleware and do not really generate files on the disk, so this Ignore rule can be omitted.
 Don't forget to add Jade type in the file extension, because Express uses the Jade template.   
5. Configure package.json

Add a command in SCRIPT to start the entire application

{… “scripts”: {“dev”: “nodemon index.js”}, …}

This is only necessary to run

npm run dev
this command can start Server simultaneously.
  Complete code has been uploaded Github, click to access  
The above is the full content of this article, I hope to help everyone, I hope everyone will support Tumi Cloud.

© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment