Build a Vue. js Project template and a vue. js Template
Preface
Since the beginning of this year (2017), our team began to introduce "Vue. js" to develop mobile products. As the leader of the team, my first task is to design the overall architecture. A good architecture must have rich development experience before it can be built. Although I have many years of front-end development experience, I am still a beginner in "Vue. js. Fortunately, "Vue. js" has a supporting tool "Vue-CLI", which provides some mature project templates, greatly reducing the difficulty of getting started. However, many specific problems need to be considered and solved by yourself.
Project Division
Most of our H5 products are embedded in the mobile client pages. The functions of each project are relatively independent and the scale is not large. In this way, these small projects can be divided into different ones, and they can also be managed in a large project. Their advantages and disadvantages are as follows:
The project Template takes into account that our team has just begun using "Vue. js" and needs to gradually find the appropriate architecture. If you make a big project, once the architecture needs to be adjusted, it is likely to hurt your strength. Therefore, the final choice is to divide the project into multiple small projects.
Although divided into multiple small projects, these small projects must maintain consistent architecture and public code. To put it bluntly, we need to build our own project template based on the business situation. All specific projects are developed based on this template. The following describes how to set up the project template of our team.
Initialization
The project template is also a project, so it is initialized through "Vue-CLI" (the project name is "webapp-public 」):
vue init webpack webapp-public
Here we use the "webpack" template, because it has complete functions. Note the following during initialization:
SASS
Installing "SASS" is relatively simple. First install related dependencies through the command line:
npm install node-sass --save-devnpm install sass-loader --save-dev
After installation, you only need to specify the "lang" attribute of the style label as "scss", you can use this language to compile the style code:
<style lang="scss" scoped></style><style src="style.scss" lang="scss"></style>
REM Layout
Nowadays, most mobile pages use rem as the unit of size in the style code to adapt to mobile phone screens of different sizes. However, the design draft provided by the designer is still in px units. This requires converting px to rem, which can be converted in your mind or through tools such as the "postcss-px2rem" plug-in of "PostCSS 」.
When initializing the project, "PostCSS" has been installed, so install "postcss-px2rem" directly:
npm install postcss-px2rem --save-dev
After installation, modify ". postcssrc. js" under the project root directory and add the "postcss-px2rem" Configuration:
"plugins": { "autoprefixer": {}, "postcss-px2rem": { "remUnit": 100 }}
The "px value/remUnit" is the converted rem value. You can modify the "remUnit" value as needed.
However, some special px values do not need to be converted to rem values, which can be prevented by the postcss-px2rem through special annotations. For example:
/* Lines under different 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 single-page application development, the "Vuex" responsible for status management is also necessary. The installation is also very simple:
npm install vuex --save
However, in some browsers of earlier versions, such exceptions may occur:
Error: [vuex] vuex requires a Promise polyfill in this browser.
This is because the browser does not support "Promise". In this case, a "polyfill" is required 」. We can directly use "babel-polyfill 」:
npm install babel-polyfill --save
"Babel-polyfill" adds new objects and methods for ES6 in the global scope. Other code in the project does not need to be explicitly introduced (import or require, this means that "Webpack" does not recognize it as a project dependency. Modify "/build/webpack. base. conf. js" and add "babel-polyfill" at the packaging entrance 」:
entry: { app: ['babel-polyfill', './src/main.js']}
In addition, "babel-plugin-transform-runtime" is installed by default when you use "Vue-CLI" to initialize a project 」, its role is repeated with that of babel-polyfill, so the former can be removed. Modify ". babelrc" in the root directory and remove this line:
"plugins": ["transform-runtime"]
Then delete the dependency:
npm uninstall babel-plugin-transform-runtime --save-dev
Access path
When a small project runs on a server (whether it is a test, a pre-release server or a production environment server), it is differentiated by a level-1 sub-directory.
This means that a directory must be added to all the paths in the project (for example, if the original access path is "http: // localhost: 8080/home", change it to "http: // localhost: 8080/project-a/home 」). Never think that this is a simple task. In fact, there are many things to change.
First, you must change the base path configuration of "Vue-Router:
New Router ({base: '/project-a/', // base path mode: 'History ', routes: [{path:'/', component: home}]});
After the base path is set, all routing-related paths are relative base paths, rather than the root directory.
Then, the development server's resource release path (/config/index. js ):
dev: { assetsPublicPath: '/project-a/' }
Also modify the "/build/dev-server.js" two places, otherwise the access will be 404:
Require ('connect-history-api-fallback') ({// The default value is "/index.html". Because the resource release path has been changed, the corresponding index is also required here: '/project-a/index.html '})
// After running the project, the default page address var uri = 'HTTP: // localhost: '+ port +'/project-a/'is displayed /'
Finally, modify the Webpack hot update detection path. Modify/build/dev-server.js first 」:
require('webpack-hot-middleware')(compiler, { log: false, path: '/project-a/__webpack_hmr' })
Then modify/build/dev-client.js 」:
require('webpack-hot-middleware/client?path=__webpack_hmr&dynamicPublicPath=true&noInfo=true&reload=true')
By the way, the above parameters are all debugging results using source code. The official documentation does not provide details.
After all the changes are completed, we can find that there are five directory-related codes. Isn't it necessary to change the code five times for a specific project? Very troublesome. In this case, it is best to write this logic into a public function for calling. New File/src/add-dirname.js 」:
const DIR_NAME = '/project-a/';module.exports = function(path) { return (DIR_NAME + path).replace(/\/{2,}/g, '/');};
Then, change all the Code involved in adding a level-1 subdirectory to call this function:
In this way, to modify a level-1 subdirectory, you only need to modify the value of the constant "DIR_NAME.
Public Code
There are three types of common code:
Databases with strong versatility: including some general libraries compiled by team members and general libraries that cannot be installed through npm, which are irrelevant to the business;
Business logic database: public code that is related to the business but not the performance layer;
Business Component Library: component at the presentation layer.
Both are located in "/src/public 」:
In the folder of each public code, the directory structure of a specific library or component is as follows:
Here, we need to mention the version number folder. If the modification to the library or component causes incompatibility with the previous call code, you should not modify the original file, but create a new version folder, put the new Code and other resource files in the new folder. The advantage of this is that when you update public code for a specific project, you can simply overwrite/src/public in the Project template without worrying about incompatibility.
Build
The "webpack" Project template has configured the building logic. You can run the following command to build the SDK:
npm run build
According to the default configuration, the code will be published to the "dist" folder under the project root directory. However, such a simple and crude release method cannot meet the actual needs:
Resource files (images, CSS, JS, etc.) should be released to the CDN server;
The resource file must be referenced through the complete URL in HTML (because the resource file is in the CDN domain );
Different Environments (test, prerelease, and production) are accessed using different domains.
First, we solve the problem of environment differentiation. In the build command, we add a parameter to indicate the environment:
npm run build <test|pre|prod>
Create a configuration file conf. json in the root directory (for simplicity, only two environment configurations are written ):
The file content represents the HTML file publishing path, resource publishing path, and resource access path in different environments.
Next, we will connect these configurations to the packaging configuration of "Webpack. Modify "/config/index. js" and add:
Var env = process. argv [2]; // environment parameter (second from 0) var conf = require ('.. /conf '); // find the configuration conf for the corresponding environment. indexRoot = conf. indexRoots [env]; conf. assetsRoot = conf. assetsRoots [env]; conf. assetsPublicPath = conf. assetsPublicPaths [env];
Then modify the building code:
build: { index: path.resolve(__dirname, conf.indexRoot + 'index.html'), assetsRoot: path.resolve(__dirname, conf.assetsRoot), assetsPublicPath: conf.assetsPublicPath}
Run the build command to release the project to the path specified by conf. json.
Summary
So far, the project template has been set up. In fact, the most important thing is configurability. Otherwise, the developer of a specific project needs to change a dozen places to initialize a project, and the efficiency will be very low.
Use of project templates
The project template has been set up, but how can it be used? There are two common scenarios:
Initialize a new project: clone or pull a project template project, copy all files of the project (except the ". git" folder) to the folder of the new project, modify the configuration, and perform subsequent development.
Update public code: clone or pull the project template project, and copy the code to be updated to the corresponding path of the target project.
Both scenarios are inseparable from "clone or pull" and "copy and paste". This approach is troublesome, and the other is too low. So I used Node. js to write a command line tool "webapp-cli" to complete these two tasks.
The command for initializing a project is:
webapp init [projectPath]
For example:
webapp init test
The command to update a specific file is:
webapp update <fileGlobs> [projectPath]
For example:
webapp update /src/public/** test
This tool does not change the operation mode, but changes from manual operation to program labor.
>
The front-end student paid attention !!!
If you have any questions or want to obtain learning resources during the learning process, join the frontend learning exchange group 461593224. Let's learn the frontend together!