Vue.js Project Template Building

Source: Internet
Author: User
Tags install node npm install node postcss

Objective

Since the beginning of this year (2017), our team has started to introduce "vue.js" to develop mobile-based products. As the leader of the team, my first task is to design the overall architecture. A good architecture must be rich in development experience before it can be built. Although I have many years of front-end development experience, but for "vue.js", is still a novice. Fortunately "vue.js" has a companion tool "vue-cli", which provides a number of more mature project templates, to a large extent, to reduce the difficulty of getting started. However, many specific problems still need to be considered and solved by themselves.

Project Division

Most of our company's H5 products are nested within the Mobile client page. Each project features a relatively independent and small size. In this way, these small projects can be fragmented, or they can be centrally placed in a large project to manage. Their advantages and disadvantages are as follows:


Project templates Considering that our team has just started using "vue.js", we need to step through the right architecture. If you make a big project, once the architecture is adjusted, it is likely to be hurt –. So the final choice is divided into multiple small projects.

Although divided into small projects, these small projects also need to maintain a consistent architecture and common code. To put it bluntly, it is to build their own project template according to the business situation, all the specific projects are developed on the basis of this template. Here's a look at the construction of our team's project templates.

Initialization

The project template itself is also a project, so it is also initialized with "vue-cli" (the project name is "webapp-public"):

vue init webpack webapp-public

Here is the "webpack" template, because the function is quite complete. In the process of initialization, be aware that:

    • Install "vue-router" to support single page applications;

    • Install the "eslint" to unify the encoding specification.

SASS

The support for installing "sass" is relatively straightforward, and the dependent dependencies are first installed via the command line:

npm install node-sass --save-devnpm install sass-loader --save-dev

Once installed, you can write style code in this language as long as you specify the "lang" property of the style tag as "scss":

<style lang="scss" scoped></style><style src="style.scss" lang="scss"></style>
REM layout

Today's mobile pages are used in the style code to accommodate the different sizes of the mobile screen, with REM as the size unit. However, the designer's design manuscript is also in PX units. This requires converting PX to REM, which can be transferred in the brain or through tools, such as the "postcss" plugin "postcss-px2rem".

When initializing the project, the "postcss" is already installed, so install the "postcss-px2rem" directly:

npm install postcss-px2rem --save-dev

After the installation, you also need to modify the ".postcssrc.js" under the project root to increase the "postcss-px2rem" configuration:

"plugins": {  "autoprefixer": {},  "postcss-px2rem": { "remUnit": 100 }}

The "PX value/remunit" is the REM value that is converted, and you can modify the value of the "remunit" as needed.

However, some special PX values do not need to be converted to REM values, which can be prevented by special annotations "postcss-px2rem" to deal with this value. For example:

/* 不同dpr下的细线 */.g-dpr-1 .g-border-1px {  border-width: 1px !important; /*no*/ } .g-dpr-2 .g-border-1px {  border-width: 0.5px !important; /*no*/ }
Vuex

In a single page application development, the "vuex" responsible for managing the state is also essential. The installation is also very simple:

npm install vuex --save

However, when used in real time, in some low-version system browsers, such exceptions may occur:

Error: [Vuex] Vuex requires a Promise polyfill in this browser.

This is because the browser does not support "promise", which requires a "polyfill". We can use "babel-polyfill" directly:

npm install babel-polyfill --save

"babel-polyfill" adds ES6 new objects and methods to the global scope, and other code in the project does not need to explicitly introduce (import or require) it, which means that "webpack" does not recognize it as a dependency on the project. So also modify the "/build/webpack.base.conf.js", add "babel-polyfill" at the packing entrance:

entry: {  app: [‘babel-polyfill‘, ‘./src/main.js‘]}

Another thing to mention is that when initializing a project with "vue-cli", the "babel-plugin-transform-runtime" is installed by default, and its function is duplicated with "babel-polyfill", so the former can be removed. Modify the ".babelrc" in the root directory to remove this line:

"plugins": ["transform-runtime"]

You can then delete the dependencies:

npm uninstall babel-plugin-transform-runtime --save-dev

Access path

Each small project actually runs on the server (whether it's a test, pre-release, or production server) and is differentiated by a sub-directory.

This means that all the paths in the project are added to a directory (for example, the original access path is "http://localhost:8080/home", which is now changed to "http://localhost:8080/project-a/home"). Do not think this is a very simple thing, in fact, there are many places to change.

The first thing to change is the "vue-router" base path configuration:

new Router({  base: ‘/project-a/‘, // 基路径 mode: ‘history‘,  routes: [ { path: ‘/‘, component: Home }]});

After the base path is set, all routes related to the route are relative to the base path, not the root directory.

Then the resource publishing path for the development Server (/config/index.js):

dev: { assetsPublicPath: ‘/project-a/‘ }

The corresponding also to modify the "/build/dev-server.js" two places, otherwise access will be 404:

require(‘connect-history-api-fallback‘)({  // 默认为"/index.html",因为资源发布路径改了,所以这里也要对应上 index: ‘/project-a/index.html‘ })
// 运行项目后默认打开的页面地址var uri = ‘http://localhost:‘ + port + ‘/project-a/‘

Finally, modify the detection path of the Webpack hot update. Modify the "/build/dev-server.js" First:

require(‘webpack-hot-middleware‘)(compiler, {  log: false,  path: ‘/project-a/__webpack_hmr‘ })

Then modify the "/build/dev-client.js":

require(‘webpack-hot-middleware/client?path=__webpack_hmr&dynamicPublicPath=true&noInfo=true&reload=true‘)

Incidentally, the above parameters are completely debug with the source code results, the official website document is not described in detail.

After all the changes can be found, directory-related code has 5, the specific project is not to use the time to change 5 times? Very troublesome. In this case, it is the best choice to write this part of logic as a public function to invoke. New file "/src/add-dirname.js":

const DIR_NAME = ‘/project-a/‘;module.exports = function(path) {  return (DIR_NAME + path).replace(/\/{2,}/g, ‘/‘);};

Then the code involved in adding a sub-directory is all changed to call the function to implement:

This way, if you want to modify the first-level subdirectory, you only need to modify the value of the constant "dir_name".

Public code

Our public code is divided into three types:

    • A more general-purpose library: includes some common libraries written by team members, generic libraries that cannot be installed with NPM, etc., which are not related to the business;

    • Business Logic Library: Public code that is relevant to the business, but not related to the presentation layer;

    • Business Component library: The component of the presentation layer.

They are all located in "/src/public":

Within each common code folder, the directory structure of a particular library or component is as follows:

    • /src/public/components/img-box

    • Img-box.vue

    • 1.1

Here is a special mention of the version number of this layer of folder. If the changes to the library or component will cause the previous calling code to be incompatible, you should not modify the original file, but instead create a new version number folder and put the new code and the remaining resource files in the new folder. The advantage of this is that when you want to update the public code for a specific project, you can simply overwrite the "/src/public" of the project template in the past without worrying about incompatibility.

Build

"webpack" This project template has been configured to build the logic. The build can be performed with a single command:

npm run build

Based on the default configuration, the code is published to the "dist" folder in the project root directory. However, such a simple and crude way of publishing does not meet the actual needs:

    • Resource files (Pictures, CSS, JS, etc.) to be published to the CDN server;

    • The resource file is referenced in HTML through the full URL (because the resource file is on the CDN domain);

    • Environments (test, pre-release, production) use different domain access.

To solve the environment-sensitive problem first, we add a parameter to the build command to represent the environment:

npm run build <test|pre|prod>

Then create a new profile in the root directory "conf.json" (for simplicity, write only the configuration of the two environments):

The file content represents the HTML file publishing path, the resource publishing path, and the resource access path in different environments.

The next step is to plug these configurations into the "webpack" package configuration. To modify the "/config/index.js", first add:

var env = process.argv[2]; // 环境参数(从0开始的第二个)var conf = require(‘../conf‘);// 找出对应环境的配置conf.indexRoot = conf.indexRoots[env];conf.assetsRoot = conf.assetsRoots[env];conf.assetsPublicPath = conf.assetsPublicPaths[env];

Then modify the code for the build section:

build: {  index: path.resolve(__dirname, conf.indexRoot + ‘index.html‘), assetsRoot: path.resolve(__dirname, conf.assetsRoot), assetsPublicPath: conf.assetsPublicPath}

When you run the build command, you can publish the project to the path specified in "conf.json".

Summary

The project template is now complete. In fact, the most important point is the configurable, otherwise, the development of the specific project of the person to initialize a project to change more than 10 places, the efficiency is very low.

Use of project templates

The project template has been set up, but how to use it? There are two common scenarios:

    • Initialize new project: Clone or pull the project template project, copy all Files of the project (except the ".git" folder) to the folder of the new project, modify the configuration for subsequent development.

    • Update common code: Clone or pull the project template project, copy the code to be updated to the corresponding path of the target project.

Both scenarios are inseparable from "cloning or pulling", "Copy and Paste", which is troublesome, and the other is to force the lattice too low. So later I wrote a command-line tool "webapp-cli" with node. js to do both of these tasks.

The command to initialize the project is:

webapp init [projectPath]

For example:

webapp init test

The commands for updating specific files are:

webapp update <fileGlobs> [projectPath]

For example:

webapp update /src/public/** test

This tool does not change the way it is done, but it is done by a manual operation into a program.

>

Learn the front-end students pay attention!!!

The learning process encountered any problems or want to acquire learning resources, welcome to join the front-end learning Exchange Group 461593224, we learn the front end!

Vue.js Project Template Building

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.