Vue.js knowledge - configuration of webpack, loader and Vue

Basic use of webpack

webpack version: 3.6.0

Create two folders under the file:

  • src, source file
  • dist to store the packaged files

src folder: write two files

Main.js (entry file)
(import method of CommonJS)

const {add,mul} = require("./aaa.js")

console.log(add(20,30));

console.log(mul(20,20));

aaa. File: imported file

function add(num1,num2){
  return num1+num2
}

function mul(num1,num2){
  return num1 * num2
}

module.exports={
  add,
  mul
}

Write index.html under the general file

Then input webpack. / SRC / main.js / dist / bundle.js in the terminal

After that, a bundle.js will be generated in the dist folder and imported in index.html to test the file.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script src="./dist/bundle.js"></script>
</body>
</html>

webpack.config.js configuration and package.json configuration

In the above, you can package by entering webpack. / SRC / main.js / dist / bundle.js in the terminal, but if you want to enter it directly
npm run build directly performs the above operations. How to set it?

Set a webpack.config.js file under the general folder. The name is fixed and cannot be changed

Set in webpack.config.js:

const path = require('path')

module.exports={
  entry:'./src/main.js',
  output:{
    path:path.resolve(__dirname,"dist"),
    filename:'bundle.js'
  }
}

loader

loader is a very core concept in webpack

  • In the previous example, we mainly used webpack to handle js code, and webpack will automatically handle the dependencies between js
  • However, in the development, not only the basic js code processing, but also css and pictures need to be loaded, including some advanced conversion from ES6 to ES5 code, TypeScript to ES5, scss, less to css, jsx,.vue file to js file, etc
  • These transformations are not supported for the capabilities of webpack itself.
  • In this case, the extended loader of webpack is required

Use steps:

  1. Install the required loader through npm
  2. Configure under the modules keyword in webpack.config.js

css file processing

In the process of project development, many styles must be added, and the styles are often written to a separate file.

  1. In the src directory, create a css file with a normal.css file
  2. The code in normal.css is very simple, that is, set the body to red

Will the normal.css file take effect at this time?
Of course not, because it is not referenced at all. It is also impossible for webpack to find him, because it needs an entry, and webpack will start from the entry to find other dependent files.

Introduce normal.css into the main.js file

require("./css/normal.css")
At this time, if you pack, an error will be reported, prompting that there must be a corresponding loader to load the normal.css file, which can be input at the terminal
npm install css-loader@x.x.x --save-dev
In the official website of webpack, you can find how to use the style loader according to the official configuration webpack.config.js file:

module:{
    rules:[
      {
        test:/\.css$/,
        use:["style-loader","css-loader"]
        //css loader is only responsible for loading css files
        //The style loader is responsible for adding styles to the DOM
        //When using multiple loader s, it is from right to left
      }
    ]
  }

At this time, a "style loader" is also found. If the style loader is not installed, the style will not be displayed even if it is repackaged. At this time, you need a style loader to handle it.

less file processing

If you want to use scss,less and style to write styles in your project, can webpack handle it?

Take less as an example, create a less file and still put it in the css folder

@fontSize: 50px;
@fontColor:orange;

body{
  font-size: @fontSize;
  color: @fontColor;
}

Enter NPM install less less loader -- save dev on the terminal to download less and less loader. After downloading, you need to enter the configuration file in the webpack.config.js file

     test: /\.less$/i,
        loader: [
          // compiles Less to CSS
          'style-loader',
          'css-loader',
          'less-loader',
        ],

Write document.writeln ("< H1 > Hello, Vue < / H1 >") in the html page, and then package successfully!

Open page:

Image file processing

Add a picture to the css file above

body{
  background-color: red;
  background: url("../img/1.jpg");
}

If you package directly at this time, an error will appear. Tip: you need a suitable loader to solve this type of file.

Enter NPM install -- save dev url on the terminal- loader@1.1.2 Download the loader of the installation url

After downloading, you need to configure it in the webpack.config.js file

{
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              //When the loaded image is less than the limit, the image will be compiled into base64 string form
              limit: 8192
            },
          },
        ],
      },

There is a limit attribute under options. If the bit size of the file is greater than the current size, the image will be compiled into a base64 string. The image can also be directly displayed on the page, but if the file is greater than the current size, an error will be reported. Prompt to download and install file loader.

After installing the file loader, if the file is larger than the size specified in the limit attribute, the image will be renamed (named according to the hash algorithm) and packaged into the dist folder. At this time, the image will not be displayed on the page. This is because the webpack will directly return the generated path (the path of the index source file) to the user, but the whole program is packaged in the dist file, So you need to configure a path

module.exports={
  entry:'./src/main.js',
  output:{
    path:path.resolve(__dirname,"dist"),
    filename:'bundle.js',
    publicPath:'dist/',//Add such a path
  },

Repackage and display.

However, it will be found that the renamed file name is too long when the webpack is packaged, and it will be packaged directly in the root directory of dist.

If there are too many files, it will appear very messy, and you don't know which file is which file. At this time, you need to make some configuration. You want the file name renamed after packaging to remain the original name. In order to prevent naming conflict, only 8 bits are reserved in the hash value, and files of the same type are in the same folder.

{
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              //When the loaded image is less than the limit, the image will be compiled into base64 string form
              limit: 8192,
              name:'img/[name].[hash:8].[ext]' //[] represents that the intermediate value is a variable and can be obtained dynamically
            },
          },
        ],
      },

At this time, it is found that there are multiple img folders under the dist folder, and the photo files are also named according to the original name and hashed.

babel from ES6 to ES5

If you carefully read the js file packaged by webpack, you will find that the syntax of ES6 is not converted to ES5. This means that some browsers that do not support ES6 cannot run the code well.

babel is needed

npm install --save-dev babel-loader@7 babel-core babel-preset-es2015 
{
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,  //exclude: except, these files are generally not packaged
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015']
          }
        }
      }

Vue configuration

In the actual project, vuejs will be used for development, and the components of vue will be organized in special files, so you need to learn to integrate vuejs in the webpack environment

First, you need to install vue. Enter npm install vue in the terminal. After downloading and installing, you need to import it in main.js

//Development using vue
import Vue from 'vue'

const app =new Vue({
  el:"#app",
  data:{
    message:"vue Medium message"
  }
})
<body>
  <div id="app">
    {{message}}
  </div>
<script src="./dist/bundle.js"></script>
</body>

However, there will be an error in the browser at this time. This error means that the current version of Vue is runtime only. There can only be a solution for the time being, and the principle is still to be seen.

It needs to be configured in webpack.config.js

resolve:{
    alias:{//alias
      'vue$':'vue/dist/vue.esm.js'
    }
  }

The difference between el and template

After the above code runs successfully, consider one question:

  • If you want to display the data in data in the interface, you must modify index.html. If you customize the component later, you must also modify index.html to use the component. However, the HTML template does not want to be modified frequently during development. Can you do this?

In the above Vue instance, the el attribute is defined to bind with #app in index.html, so that the Vue instance can manage its contents. Now delete the {message}} content in the div element, and only retain the div element with the most basic id of app, but still want to display the content of {message}. What should I do?

First, define a template attribute. The code is as follows:

//main.js
new Vue({
  el:"#app",
  template:`
  <div>
	<h2>{{message}}</h2>
  </div>
  `,
  data:{
    message:"vue Medium message"
  }
})

The code is repackaged and the page still displays message

Now, if you want to separate components from instances, how do you do it?

  1. First, create an App.vue file. The template is as follows:
//App.vue
<template>
  //Template for writing components
</template>

<script>
export default {
	name="App",
	//Write the properties of the component
}
</script>

<style>
//Write the style of the component
</style>
  1. You can copy attributes from an instance to a. vue file:
//App.vue
<template>
  <div>
    <h2>{{message}}</h2>
  </div>
</template>

<script>
export default {
  name:"App",
  data(){
    return {
      message:"This is vue Information in file",
    }
  }
}
</script>

<style>
  h2{
    color: blue;
  }
</style>
  1. After creating the component, you need to import it in the main.js file
import App from './vue/App.vue'

new Vue({
  el:"#app",
  template:'<App/>',
  components:{
    App
  }

})

4. However, it cannot be loaded directly at this time because it is a new format file and requires a special loader:
npm install vue-loader vue-template-compoler --save-dev

5. After installation, you also need to configure the webpack.config.js file

      {
        test:/\.vue$/,
        use:["vue-loader"]
      }
    ]

Keywords: Javascript node.js Front-end Vue.js

Added by d-woo on Fri, 03 Sep 2021 23:53:22 +0300