Zero-based: How the directory structure of a formal Vue+webpack project is formed

Source: Internet
Author: User
Tags postcss

Learn a little bit of programming every day PDF ebook, video tutorial free download:
Http://www.shitanlife.com/code

How to build a vue+webpack front-end project workflow from scratch first we start with the directory structure of the project. What does a directory structure that continues to evolve, continually adds new features, and facilitates post-maintenance? The next leap uncle to take you hand to learn together.

Primary front end Initialization Directory Chapter

At the beginning of the project, we must first enter the <project name> root directory on the terminal Terminal Command Line (hereinafter referred to as the terminal) CD, and then enter the npm init initialization of a NPM project, A Package.json file appears under the project root directory. Then you can install the dependencies and enter them directly in the terminal npm i webpack vue vue-loader -D . When we put these several installed, terminal will prompt us warn (warning?? ):


The main idea is that Vue-loader needs a css-loader and Vue-template-compiler as its third-party reliance, so listen to it and we go through the installation:

npm i css-loader vue-template-compiler -D

The following warning message indicates that we are missing some information, which is really irrelevant, so we don't need to care about it.

With this simple few steps, our project is initialized. Then create a src folder under the root directory, which is the directory we put in the source code. Then we create a new App.vue file under the SRC directory, where we can write some business code about the project:

<template>    <div id="test">{{text}}</div></template><script>    export default {        data () {            text: ‘闰土大叔‘ } }</script><style>#test{ font-size:12px; color:green;}</style>

Of course, the suffix of the. vue file is not allowed to run directly in the browser, we need to find a way to get it running.

Now we want to create a new Webpack.config.js file in the project root directory, Webpack is to help us to package resources, front-end resources have many different types, such as javascript,css,html,image,iconfont and other resources are required through the HTTP Request to load something. Webpack is to upload a JS file to the browser side, and then go to render all the content. So, many times, we can put the JS file as the entry file of the project.

At this time, we create a new index.js in the SRC directory as a portal file, and write something in it:

‘vue‘import App from ‘./app.vue‘const root = document.createElement(‘div‘)document.body.appendChild(root)new Vue({    render: (h) => h(App)}).$mount(root)

After Index.js is ready, you can write it in Webpack.config.js:

const path = require(‘path‘)module.exports = {    entry:  path.join(__dirname, ‘src/index.js‘),    output: {        filename: ‘bundle.js‘,        path: path.join(__dirname, ‘dist‘)    }}

In the above code, __dirname represents the directory address where the file is located, and Path.join () is a concatenation of the string paths that follow, forming an absolute path.

All the files are then packaged into a bundle.js file via Webpack and are code that can be run directly inside the browser. Now we can add a script to the Scripts object in the Package.json file:

"scripts": {    "build": "webpack --config webpack.config.js"}

See here, there must be children's shoes to ask, why to call Webpack in here and not in the terminal directly run it?

Because only call webpack here, it will first call the Webpack version installed in our project, if we enter Webpack in the command line, it will mobilize the global webpack, This time the global webpack may be inconsistent with the Webpack version of our project, so it is prudent to take this approach.

After writing, we can run in the terminal input npm run build , will be embarrassed to find the error:


This error tells us that we need to declare a loader for the. Vue file. Because Webpack native is only supported by the JS file type and only supports the ES5 syntax, we use a number of tools to help it when we are using syntax that goes beyond its scope of understanding. So we're going to continue writing in the Webpack.config.js file:

module: {    rules: [        {            test: /.vue$/,            loader: ‘vue-loader‘        }    ]}

After adding this paragraph, we go to terminal execution npm run build , you will find that the project root directory more than a Dist folder, click on the inside found Webpack for our automatic packaging generated a bundle.js file, interested in children's shoes can point open this JS file to see:

It has a lot of code, which is inherent in the Webpack code, the code is to deal with the module dependencies in the project, because we have a lot of JS mutual dependency.


Down to more than 100 lines of time, you will find a lot of code is actually vue source. Because our project is dependent on Vue.js, Webpack will pack the Vue.js file in.


You can use the shortcut command (Ctrl) + F to find the keywords $mount See, the Red Line circled this code is our own code, in fact, Webpack do the work is to put these different types of static resources into a JS, and then we quoted in the HTML JS , you can run it normally.

I believe that we do the front-end know, in doing a project development, we want to put some fragmented JS files together, this can reduce the HTTP request. Similarly, we want to use module dependencies, because there are many reusable code in the project, write it into a module, so that when we go to write a new project, we do not have to write the original code again, or a copy.

Of course, we haven't mentioned it for the time being. BABELRC,. Eslintrc, Editorconfig, Postcss.config.js, and so on, we'll leave them behind to talk.

Intermediate front-end rational refinement of the catalogue chapter


After the initialization work is complete, we will subdivide the directory next. First we need to create a new folder at the root of the project called Build, and put the Webpack files in this folder alone. Because we will use a lot of different related files in the project configuration, then create a new Webpack.config.base.js file, we put the webpack inside the common configuration needed to put in this base file. such as the development environment and the formal environment, as well as the later we want to mention the server-side rendering environment. We all rely on base for this configuration.

The following is the code in the Webpack.config.base.js file:

Const PATH = require (' path ') const Createvueloaderoptions = require ('./vue-loader.config ') Const ISDEV = Process.env.NODE_ENV = = =' development ' Const CONFIG = {target:' Web ', Entry:path.join (__dirname,‘.. /client/index.js '), output: {filename:' Bundle. [Hash:8].js ', Path:path.join (__dirname,test:/\. ( VUE|JS|JSX) $/, loader:  ' Eslint-loader ', exclude:/node_modules/, enforce:  ' pre '}, {test:/\.vue$/, Loader:  ' Vue-loader ', Options:createvueloaderoptions (Isdev)}, {test:/\.jsx$/, Loader:  ' Babel-loader '}, {test:/\.js$/, Loader: test:/\. ( GIF|JPG|JPEG|PNG|SVG) $/, use: [{loader:  ' Url-loader ', options: { limit:1024, Name:  resources/[path][name].[ Hash:8]. [Ext] '}}]}]}}module.exports = config           

Then we create a new webpack.config.client.js, this client file relies on the base file, on this basis to extend some other configuration. So we need to webpack.config.client.js a line of code into the base file:

const baseConfig = require(‘./webpack.config.base‘)

After the basic work is done, how do we extend the configuration? First, in the Terminal Terminal Command line installation npm i webpack-merge -D We need to webpack-merge this tool to help expand, Merge different Webpack configurations, and then determine how the configuration should be combined according to the Isdev that are declared well.

The following is the code in the Webpack.config.client.js file:

Const PATH = require (' path ') const Htmlplugin = require (' Html-webpack-plugin ') const WEBPACK = require (' Webpack ') const merge = require (' Webpack-merge ') const Extractplugin = require (' Extract-text-webpack-plugin ') const BASECONFIG = require ('./webpack.config.base ') Const ISDEV = Process.env.NODE_ENV = = =' development ' const DEFAULTPLUGINS = [New Webpack. Defineplugin ({' process.env ': {node_env:isdev?' "Development" ':' "Production"}), new Htmlplugin ()]const devserver = {port:8000, host:' 0.0.0.0 ', overlay: {errors:True}, hot:TrueLet configif (Isdev) {//development environment Configuration Config = merge (Baseconfig, {devtool:' #cheap-module-eval-source-map ', module: {rules: [{Test:/\.styl/, use: [' Vue-style-loader ',' Css-loader ',///{//loader:' Css-loader ',//options: {//module:True,//Localidentname:isdev?' [Path]-[name]-[hash:base64:5] ':' [Hash:base64:5] '//}//}, {loader:' Postcss-loader ', options: {Sourcemap:True},' Stylus-loader '}]}, Devserver, Plugins:defaultPlugins.concat ([New Webpack. Hotmodulereplacementplugin (), New Webpack. Noemitonerrorsplugin ()])})}else {//formal environment configuration config = merge (Baseconfig, {entry: {App:path.join (__dirname,  ' [name ]. [Chunkhash:8].js '}, module: {rules: [{test:/\.styl/, use:ExtractPlugin.extract ({Fallba CK:  ' Css-loader ', {loader:  ' Postcss-loader ', options: {sourcemap: true }},  ' vendor '}), new Webpack.optimize.CommonsChunkPlugin ({name: 

Finally, this SRC folder we want to rename, called the client, because we later also write the service side of the code, corresponding to the name of the server, just corresponding to its meaning. This looks like the name becomes more reasonable.

When we are all right, we must remember to webpack.config.base.js and webpack.config.client.js inside the SRC path to change, replace the client, otherwise it will error.


The above is the final form of the directory structure of our project, the client directory has assets, layout, views of the three folders, including the assets directory of static resources, such as images, styles and so on; layout directory delegating components of a common layout ; Views directory The components of the specific business code are decentralized.

Of course, this directory can also be broken down with the development of the project, here will not unfold the narrative.

Written in the last

We must note that in our formal development projects, the creation of a project projects, we must first put the directory structure straighten out, the organization must be clear. In each directory structure put what things, in mind must first have a concept. Do not put the new files in the future, because once the project is bigger, maintenance time is relatively long, maybe two or three months there is a file you do not touch it. It's a very uncomfortable thing if you're going to find something and you can't find it.

The most important thing is that the clutter of the directory structure can lead to a very low efficiency of your subsequent development projects.

The topic of "How the directory structure of a formal project is formed" is here, what will I say after my article? The article previews as follows:

    • Eslint Tips for bug fixes
    • How the Vue-loader is configured
    • How do you answer the "understanding of the Vue life cycle" to make the interviewer happy?
    • Talking about the disposition of Css-module
    • ......
    • Formal environment packaging and asynchronous module packaging optimization

Learn a little bit of programming every day PDF ebook, video tutorial free download:
Http://www.shitanlife.com/code

Zero-based: How the directory structure of a formal Vue+webpack project is formed

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.