Compile ES6+ code using Webpack

Create the webpack-demo-vue folder and open it with vscode

Exhale terminal

1. The inputyarn init -y

You can automatically generate a package.json configuration file

2. Install webpack and the Webpack command line toolyarn add webpack webpack-cli -D

Note that -d, Webpack, and webpack-CLI are not involved in the production environment, so they are installed in the development environment

You can see the node_modules folder, which is used to hold various installation packages; Yarn-lock files do not need to be handled; they are used to lock dependent versions

Json includes the devDependencies configuration item, which contains the two tools we just installed

3. Continue the installationyarn add babel-loader @babel/core @babel/preset-env -D

Babel-loader is required to compile ES using Babel in webpack

@babel/core Es code compilation core

@babel/preset-env conversion rule, high VERSION ES to low version, ES6+ code to ES5

4. Create SRC folder → create index.js

Write ES6 code in index.js

[1.2.3].map(item= >console.log(item))
Copy the code

If you are not globally installed with webpack-CLI, you need to add the directive “build”: “webpack –config./webpack.config.js” to package.json.

Then run the yarn build command to compile the code, or go to node_modules/. Bin /webpack and enter./node_modules/. Bin /webpack. The dist folder and compiled files are automatically generated in the root directory

If you open dist/main.js, you can see that this is not the result we want, the arrow function is still the arrow function

5. Next we need to create webpack.config.js in the root directory for configuration

const path=require('path')// The module that handles the path

module.exports={// Output configuration
  mode:"production".// The default is production mode
  entry:"./src/index.js".// Import file
  output: {path:path.join(__dirname,"dist"),// Output the absolute path to the execution file (referring to webpack.config.js)
    filename:"boundle.js"// Specify the output file name instead of main.js
  },
  module: {rules:[
      {
        test:/\.js$/.// Matches the js file
        exclude:/node_modules/.// Ignore the node_modules folder
        use:{
          loader:'babel-loader'.options: {presets: ['@babel/preset-env'}}}]}}Copy the code

Executing YARN Build at this point outputs the desired result

6. Create HTML pages using htMl-webpack-plugin

Install yarn add html-webpack-plugin -d. This plugin will automatically import JS files

Webpack. Config. Js configuration

const path=require('path')
const HtmlWebpackPlugin=require('html-webpack-plugin') 

module.exports={
  ...
  plugins: [new HtmlWebpackPlugin({// Create an instance
      filename:'index.html'.// Specify a file name
      template:path.resolve(__dirname,'src/index.html')// Import path}})]Copy the code

Although the index. HTML import path is configured in webpack.config.js, we have not yet created → create index. HTML in the SRC folder

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
</head>
<body>
  <div id="root">
    <span>Garlic tortoise</span>
  </div>
</body>
</html>
Copy the code

Yarn Build compile. In the following figure, you can see that the index.html file in SRC is successfully compiled in the dist folder and js files are automatically imported

Start compiling Vue files

1. Install Vue tools

Yarn Add Vue Install the VUE

Yarn add vue-loader -d Installs vue-loader and parses the. Vue file

Yarn add VUe-template-compilervue-template-compiler Compiles vUE templates

2. Create related files in the SRC folder

To create the App. Vue

<template> <div class="app"> <h1> app file </h1> <span>{{MSG}}</span> </div> </template> <script> export default {name: ", data () {return {MSG :" garlic "}}} </script>Copy the code

Delete the contents of index.html, leaving only a div to mount app.vue

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
</head>
<body>
  <div id="root">
  </div>
</body>
</html>
Copy the code

Write the core entry file index.js again, delete the previous test code

import Vue from 'vue'
import App from './App.vue'

new Vue({
  el:"#root".// Mount the HTML node
  render:h= >h(App) Function (createElement){return createElement(App)}
})
Copy the code

Configure webpack.config.js. Note the introduction of vue-plugin, the addition of rules in module, and the addition of plugins

const path=require('path')
const HtmlWebpackPlugin=require('html-webpack-plugin') 
const VueLoaderPlugin=require('vue-loader/lib/plugin')

module.exports={
  mode:"production".// The default is production mode
  entry:"./src/index.js".// Import file
  output: {path:path.join(__dirname,"dist"),// Output the absolute path to the execution file (referring to webpack.config.js)
    filename:"boundle.js"// Specify the output file name instead of main.js
  },
  module: {rules:[
      {
        test:/\.js$/.// Matches the js file
        exclude:/node_modules/.// Ignore the node_modules folder
        use:{
          loader:'babel-loader'.options: {presets: ['@babel/preset-env'}}}, {test:/\.vue$/,
        use:{
          loader:'vue-loader'}}},plugins: [new HtmlWebpackPlugin({// Create an instance
      filename:'index.html'.// Specify a file name
      template:path.resolve(__dirname,'src/index.html')// Import path
    }),
    new VueLoaderPlugin()
  ]
}
Copy the code

After compiling, open index.html in the dist folder in the browser. As shown in the following figure, you can see that the Vue file has been successfully compiled

3. Configure the local service

Yarn add webpack-dev-server -d and add a line “start”: “webpack-dev-server –open” to the scripts of package.json. The –open parameter enables the project to open directly in the default browser

Ok, the command line input yarn start, the result is an error, as shown in the following figure

Tool class problems, general search can not find a solution, the best is to go to Github to find, most of the solution

The reason is that the versions are incompatible, as shown in the figure below

Go back to version 3.3.12, uninstall webpack-cli→yarn remove webpack-cli, and install the specified version yarn add [email protected] -d. Then enter yarn start, as shown in the following figure. Success!

4. Parse the CSS

CSS code was not written in the previous project, and webpack requires CSS-loader and style-loader to compile CSS code.

To install the two Loaders, run yarn add CSS-loader style-loader -d

The configuration sequence of the Loader is opposite to the loading sequence. If the configuration sequence is as follows, an error message is displayed

{
  test:/\.css$/,
  use:[
    'css-loader'
    'style-loader']},Copy the code

You need to load csS-loader first, then load style-loader to load CSS into the page, webpack.config.js configuration is as follows

.module:{
   ...
      {
        test:/\.vue$/,
        use:{
          loader:'vue-loader'}}, {test:/\.css$/,
        use:[
          'style-loader'.// Two Loaders are replaced in sequence
          'css-loader']}]},... }Copy the code

Add CSS code to app.vue

<template> <div class="app"> <h1> app file </h1> <span>{{MSG}}</span> </div> </template> <script> export default {name: ", data () {return {MSG :" "}}} </script> <style> app{color: red; } </style>Copy the code

Yarn start Is successful

5. What if you usually use sass?

Install node-sass and sas-loader → YARN add node-sass sas-loader -d

If node-sass fails to be installed, use dart-sass instead →yarn add node-sass@npm:dart-sass

Configure webpack.config.js and update rules

.module: {rules: [{...test:/\.(sa|c)ss$/.// Matches both SASS and CSS
        use:[
          'style-loader'.'css-loader'.'sass-loader'/ / new sass - loader]}]},...Copy the code

Update the style section in app.vue to use sass syntax

<style lang="sass">
  .app{
    color: red;
    span{
      color: green;
    }
  }
</style>
Copy the code

After YARN start, the span font in the browser is green

This concludes the main content of this article.

6. Some questions

  • I found some problems during the project. 🌰 such as: app. vue file if you do not write suffix will report errors, lazy cancer attack do not want to write how to do

To solve this problem, simply configure it in webpack.config.js

.module.exports={
  mode:"production".// The default is production mode
  resolve: {extensions: ['.vue'.'.js'] // Allows users to import modules without extensions, i.e. file suffixes. Depending on the document, if there are multiple files with the same name but different suffixes, WebPack will parse the files with the suffixes listed at the top of the array and skip the rest.
  },
  entry:"./src/index.js".// Import file. }Copy the code
  • Another problem: how to fix this: when we make changes to HTML data, instead of hot updates, the browser refreshes itself after a period of time?

The configuration in webpack.config.js is as follows

.const webpack=require('webpack')/ / 1

module.exports={
 ...
  plugins: [new HtmlWebpackPlugin({
      filename:'index.html'.template:path.resolve(__dirname,'src/index.html')}),new VueLoaderPlugin(),
    new webpack.HotModuleReplacementPlugin()  //2 Introduce the hot update module].devServer: {/ / 3
    hot:true}}Copy the code

Add code to the entry page

import Vue from 'vue'
import App from './App'

if(module.hot){
  module.hot.accept(error= >{// Accept is to accept hot updates
    if(error)console.log('Hot replacement error'); })}new Vue({
  el:"#root".render:h= >h(App) 
})
Copy the code

Run the project at this point, and then modify the page content. You will find that the content is changed 5 seconds later without refreshing the page.

This high latency is obviously not what we need, this is caused by mode:’production’ in webpack.config.js, change to development mode, and you’ll find, well! How sweet!

Github link for DEMO