Front-end engineering foundation - vue

Support more functions from shallow to deep

 

1. Install the latest version of node.js and NPM, and understand the basic usage of NPM.

2. Create a directory demo. Use npm to initialize the configuration: npm init, there will be a series of options after execution, you can press Enter to quickly confirm, and generate a package.json file in the demo.

3. Install webpack locally: npm install webpack --save-dev

--save-dev will install webpack as a development dependency. After the installation is successful, there will be one more configuration in package.json

"devDependencies": {
  "webpack": "4.6.0"  
}

4. Then you need to install webpack-dev-server, which can provide many services in the development environment, such as starting a server, hot update, interface proxy, etc.

Partial installation: npm install webpack-dev-server --save-dev

5. Create a js file under demo: webpack.config.js initialization content:

var config = {
    
};

module.exports = config;

6. Add a script to quickly start the webpack-dev-server service in the script of package.json:

{
  //...
    "scripts":{
          "test":*****,
          "dev":"webpack-dev-server --open --config webpack.config.js"        
      }    
    
}

When running npm run dev it will execute the webpack-dev-server --open --config webpack.config.js command. Where --config is the path to the configuration file read by webpack-dev-server, and the webpack.config.js file we created in the previous step is directly read here. --open will open the browser page when executing the command. The default address is 127.0.0.1:8080, but both ip and port can be configured.

"dev":"webpack-dev-server --host 172.172,172.1 --port 8888 --open --config webpack.config.js"

Generally, the default local address can be used.

7. Create an empty main.js file in the demo directory as the entry file, and then output and configure the entry in webpack.config.js:

var path = require('path');
var config = {
    entry: {
        main: './main'
    },
    output: {
        path: path.join(__dirname, '/dist'),
        publicPath: './dist',
        filename: 'main.js'
    }
};

module.exports = config;

The main in the entry is the single entry we configured, and webpack will start working from the main.js file. The path option in output is used to store the output directory of the packaged file, which is required. publicPath is the resource file reference directory. If it is on the cdn, you can fill in the cdn address here. filename is used to specify the name of the output file. Therefore, the output configured here means that the packaged file will be stored in demo/dist/main.js, and it can only be imported in html.

<body>
    <div id="app">Hello world</div>
<script src="/dist/main.js"></script>
</body>

8. Run npm run dev to see the words hello world.

 

9. Gradually improve the configuration file

In the world of webpack, every file is a module, like .css, .js, .html, .jpg, .less, etc. Different modules need to be handled with different loaders, and the loader is the most important function of webpack.

Install style-loader and css-loader to handle css styles.

Install via npm:

npm install css-loader --save-dev

npm install style-loader --save-dev

After the installation is complete, configure the Loader in the webpack.config.js file to increase the processing of the .css file.

var config = {
    //.....
    module:{
        rules:[
            {
                test:/\.css$/,
                use:[
                    'style-loader',
                    'css-loader'
                ]
            }
        ]
    }
};

A series of loaders can be specified in the rules attribute of the module object, and each loader must contain two options, test and use. The meaning of this paragraph is that when a require() or import statement imports a file with a suffix of .css during webpack compilation, it is first converted by css-loader, then converted by style-loader, and then continues to be packaged . The value of the use option can be an array or a string. If it is an array, its compilation order is from back to front.

Create a new style.css file under demo and import it in main.js:

/**style.css**/

#app{
  font-size:24px;

  color:#f50;
}

//main.js

import './style.css'

Re-execute npm run dev and you can see that the page text has become red and the font size has become larger.

The following is the html source code after execution:

It can be seen that css is written by dynamically creating style tags through javascript, which means that the style codes have been compiled in the mian.js file, but this may not be desirable in actual business, because the style of the project is large. There will be a lot, and they will take up too much space in js. At this time, the plugin of webbpack will be used.

Webpack's plugins are powerful and customizable. Here we use an extract-text-webpack-plugin plugin to extract the css scattered around, and generate a main.css file, and finally load it in the form of link in index.html.

 10. Install the extract-text-webpack-plugin plugin via npm:

npm install extract-text-webpack-plugin --save-dev

Then import the plugin in the configuration file and rewrite the loader configuration:

 

var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var config = {
    //.....
    module:{
        rules:[
            {
                test:/\.css$/,
                use:ExtractTextPlugin.extract({
                    use: 'css-loader',
                    fallback: 'style.loader'
                })
            }
        ]
    },
    plugin: [
        // Rename the extracted css file 
        new ExtractTextPlugin("main.css" )
    ]
};

module.exports = config;

At this time, an error similar to "DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead" may appear when running, this is a webpack version problem

Installing 4.0 with sudo npm install extract-text-webpack-plugin@next solved the problem.

 

11. Single-file components and vue-loader

When building Vue projects with webpack, there is a new build mode available: .vue single-file components. Using vue-loader in webpack can process files in .vue format.

A .vue file generally contains 3 parts, <template>, <script>, <style>

The style tag uses the scoped attribute, indicating that the current CSS is only valid for this component. If it is not added, the style will be applied to the entire project. style can also be used in conjunction with CSS precompilation. For example, less processing can be written as <style lang="less">. To use the .vue file, you need to install vue-loader, vue-style-loader and other loaders and configure them. Because to use es6 syntax, you also need to install loaders such as babel and babel-loader. Install the following dependencies one by one using npm:

npm install --save vue

npm install --save-dev vue-loader

npm install --save-dev vue-style-loader

npm install --save-dev vue-template-compiler

npm install --save-dev vue-hot-reload-api

npm install --save-dev babel

npm install --save-dev babel-loader

npm install --save-dev babel-core

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

npm install --save-dev babel-preset-es2015

npm install --save-dev babel-runtime

12. After the installation is complete, configure in webpack.config.js to support parsing of .vue files and es6.

var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var config = {
    entry: {
        main: './main'
    },
    output: {
        path: path.join(__dirname, '/dist'),
        publicPath: '/dist',
        filename: 'main.js'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders :{
                        css: ExtractTextPlugin.extract({
                            use: 'css-loader',
                            fallback: 'vue-style-loader'
                        })
                    }
                }
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    use: 'css-loader',
                    fallback: 'style-loader'
                })
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin("main.css")
    ]
};

module.exports = config;

When vue-loader compiles .vue files, it will process <template>, <script>, <style> separately, so there is an option in the vue-loader option to further configure different languages. For example, when processing css, it will be parsed by css-loader first, and then the processing result will be handed over to vue-style-loader for processing. When the technology stack is diversified, you can specify different languages ​​for <template>, <script>, and <style>, such as <template lang="jade"> and <style lang="less">, and then configure the loader. .

13. Create a new file named .babelrc in the demo directory and write the babel configuration. Webpack will rely on this configuration file to use babel to compile es6 code:

{
  "presets": ["es2015"],
  "plugins": ["transform-runtime"],
  "comments": false
}

After configuring these, you can use the .vue file. Each .vue file represents a component, and components can depend on each other.

14. Create a new app.vue file in the demo directory and write the following content:

<template>
    <div>Hello {{name}}</div>
</template>

<script>
    export default {
        data() {
            return {
                name: "vue.js"
            }
        }
    }
</script>

<style scoped>
    div{
        color: #f60;
        font-size: 24px;
    }
</style>

The .vue component does not have a name, and it can be customized when the parent component is used. Once the component is written, it can be used in the entry main.js. Open main.js and replace the content with the following code:

import Vue from 'vue' ;
 // import app.vue component 
import App from './app.vue' ;

// Create a Vue instance 
new Vue({
    el: "#app",
    render: h => h(App)
});

 

render:h => h(App) is written in es6, which is equivalent to

render:function(h){

  return h(App)

}

Execute npm run dev, so that the first vue project will run.

bug: This place is incompatible with vue-loader upgrade to version 15 and above. Need to go back to version 14 to be compatible.

The reason why there is a bunch of data-v-xxx content here is because the <style scope> function is used. If the scope is removed, there will be no more.

15. Create two new files in the demo directory, title.vue and button.vue 

 title.vue

<template>
    <h1>
        <a :href="'#' + title">{{title}}</a>
    </h1>
</template>

<script>
    export default {
        props:{
            title:{
                type:String
            }
        }
    }
</script>

<style scoped>
    h1 a {
        color: #3399ff;
        font-size: 24px;
    }
</style>

button.vue

 

<template>
    <button @click="handleClick" :style="styles">
        <slot></slot>
    </button>
</template>

<script>
    export default {
        props: {
            color: {
                type: String,
                default: '#00cc66'
            }
        },
        computed:{
            styles () {
                return {
                    background: this.color
                }
            }
        },
        methods:{
            handleClick:function(e){
                this.$emit('click',e);
            }
        }
    }
</script>

<style scoped>
    button{
        border: 0;
        outline: none;
        color: #fff;
        padding: 4px 8px;
    }
    button:active{
        position: relative;
        top: 1px;
        left: 1px;
    }

</style>

Then rewrite the root instance app.vue component and import title.vue and button.vue:

<template>
    <div>
        <v-title title="Vue componentization"></v-title>
        <v-button @click="handleClick">Click button</v-button>
    </div>
</template>

<script>
    // Import components 
    import vTitle from './title.vue' ;
    import vButton from './button.vue';

    export default {
        components: {
            vTitle,
            vButton
        },
        methods:{
            handleClick:function(e){
                console.log(e)
            }
        }

    }
</script>

<style scoped>
    div {
        color: #f60;
        font-size: 24px;
    }
</style>

where components: {

  vTitle,

  vButton

}

The writing method is es6 writing, which is equivalent to:

components: {

  vTitle : vTitle,

  vButton : vButton

}  

The imported components are locally registered, and their names can be customized. Other usages are the same as those of the components.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325388385&siteId=291194637