Now we almost use VUE-CLI to create projects, because it provides almost all the functions we need, no longer need to configure our own functions like Webpack, ESLint, SASS/LESS, Unit test/ E2E test, which greatly improves our efficiency. So we don’t go into the technical details, just know how to use it. This is certainly not enough for a front-end, not to say proficient, but also must have a certain understanding of its principle. So today we create a Vue project from scratch without vue-CLI.

Create a project

mkdir vue-webpack
cd vue-webpack
npm init -y
Copy the code

Create entry file

Create the SRC folder and create the main.js file

alert('hello vue')
Copy the code

Next, create the index.html file

<! DOCTYPEhtml>
<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>Vue Webpack</title>
</head>
<body>
    <div id="app">
    </div>
</body>
</html>
Copy the code

Project directory

src/
    main.js
    index.html
Copy the code

Webpack basic installation configuration

npm install webpack webpack-cli -D
Copy the code

Then create webpack.config.js in the root directory

const path = require('path')

module.exports = {
  mode: 'development'.entry: './src/main.js'.output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js'.clean: true,}}Copy the code
  • Entry is an entry file read by Webpack. There can be more than one entry file, but generally a single-page application has only one entry file
  • Output is a packaged output configuration
    • Path package directory, which I configured as the dist folder
    • Filename Specifies the name of the packaged file
    • Clean Indicates whether to clear folders before packing

Modify package.json to change scripts to the following

"scripts": {
    "watch": "webpack --watch",
    "build": "webpack"
},
Copy the code
  • — Watch will listen for file changes and automatically package

Test whether packaging is successful

npm run build

# Pack successfullyAsset. The main e8760e604a32a49cb09a. Js 1.18 KiB [emitted] [immutable] (name: / SRC /main.js 1 bytes [built] [code generated] webpack 5.51.2 compiled successfullyin 59 ms
Copy the code

After successful packaging, the dist folder is generated

dist/
    main.e8760e604a32a49cb09a.js
Copy the code

The HTML file is missing. Let’s install a Webpack plug-in

npm install html-webpack-plugin -D
Copy the code

Modify the webpack. Config. Js

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

module.exports = {
  mode: 'development'.entry: './src/main.js'.output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js'.clean: true,},plugins: [
    new HtmlWebpackPlugin({ template: './src/index.html'}})]Copy the code
  • The html-webpack-plugin will automatically inject wrapped JS into index.html

Retest packaging

npm run build
Copy the code

After successful packaging, the dist folder is generated

dist/
    index.html
    main.e8760e604a32a49cb09a.js
Copy the code

Open index.html in your browser and it will pop up ·’ Hello vue’

Vue installation and configuration

Next, install the VUe-related configuration

Install the Vue and Vue Router

npm install vue vue-router
Copy the code

The installation package.VueWebpack configuration of the file

npm install vue-loader vue-template-compiler -D
Copy the code

Note that the VUE version must be consistent with that of vue-template-Compiler; otherwise, errors may occur

Modify main.js as follows

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'

import Foo from './pages/Foo.vue'
const Bar = () = > import(/* webpackChunkName: "group-bar" */ './pages/Bar.vue') // Load files asynchronously

Vue.use(VueRouter)

const routes = [
  { path: '/foo'.component: Foo },
  { path: '/bar'.component: Bar }
]

const router = new VueRouter({
  routes
})

new Vue({
  router,
  render: (h) = > h(App),
}).$mount('#app');
Copy the code

Create the SRC/app.vue file

<template>
  <div>
    <h1>hello vue webpack</h1>
    <ul>
      <li>
        <router-link to="/foo">Go to Foo</router-link>
      </li>
      <li>
        <router-link to="/bar">Go to Bar</router-link>
      </li>
    </ul>
    <router-view></router-view>
  </div>
</template>
Copy the code

Create the Pages folder under SRC and create the bar. vue and foo. vue files

Bar.vue

<template>
  <div>bar</div>
</template>
Copy the code

Foo.vue

<template>
  <div>foo</div>
</template>
Copy the code

Modify the webpack. Config. Js

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

module.exports = {
  mode: 'development'.entry: './src/main.js'.output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js'.clean: true,},module: {
    rules: [{test: /\.vue$/,
        loader: 'vue-loader'}},],plugins: [
    new webpack.ProgressPlugin(),
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({ template: './src/index.html'}})]Copy the code
  • Webpack.progressplugin () users get a progress bar when they pack

And then packaged

npm run build
Copy the code

You can see the dist directory

dist/
    index.html
    group-bar.3235a6c307cef33d5703.js
    main.406dcc2772a126d0094b.js
Copy the code

Open index. HTML in the browser. The test finds that the page is displayed normally and there is no problem with route switching

Install the Element UI framework

npm install element-ui
Copy the code

Here, select components that import Element UI on demand, not in full, so install the following dependencies

npm install @babel/core babel-loader babel-plugin-component css-loader
Copy the code

Modify main.js to introduce a Button component and a Calendar Calendar component

import Vue from 'vue'
import VueRouter from 'vue-router'
import { Button, Calendar } from 'element-ui';
import App from './App.vue'

import Foo from './pages/Foo.vue'
const Bar = () = > import(/* webpackChunkName: "group-bar" */ './pages/Bar.vue') // Load files asynchronously

Vue.use(VueRouter)
// el component
Vue.use(Button)
Vue.use(Calendar)

const routes = [
  { path: '/foo'.component: Foo },
  { path: '/bar'.component: Bar }
]

const router = new VueRouter({
  routes
})

new Vue({
  router,
  render: (h) = > h(App),
}).$mount('#app');
Copy the code

Create a. Babelrc file in the root directory to configure the on-demand import components of Babel

{
    "plugins": [["component",
        {
          "libraryName": "element-ui"."styleLibraryName": "theme-chalk"}}]]Copy the code

Modify the webpack. Config. Js

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

module.exports = {
  mode: 'development'.entry: './src/main.js'.output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js'.clean: true,},module: {
    rules: [{test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader'
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader'.'css-loader'] {},test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource'}, {test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource'}},],plugins: [
    new webpack.ProgressPlugin(),
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({ template: './src/index.html'}})]Copy the code

Modify the app. vue file

<template> <div> <h1>hello vue webpack</h1> <ul> <li> <router-link to="/foo">Go to Foo</router-link> </li> <li> <router-link to="/bar">Go to Bar</router-link> </li> </ul> <router-view></router-view> <el-calendar V-model ="value"></ el-button> <el-button> Default button </el-button> <el-button type="primary"> Main button </el-button> <el-button </el-button> <el-button type="info"> </el-button> <el-button type="warning"> <el-button type="danger"> </el-button> </div> </template> <script> export default {data() {return {value: new Date() } } } </script> <style scoped> h1 { color: blue } </style>Copy the code

packaging

npm run build
Copy the code

Open index.html in your browser and test the route switching. The Element component displays normally

Webpack other configurations

Finally, there are some other useful configurations

  • Webpack-dev-server is used for automatic refresh and module hot replacement during development to improve development efficiency
  • When the source-map code encounters an error, you can directly find the line of the file
  • Optimization’s runtimeChunk, splitChunks configuration to configure packaged code fragmentation, project dependencies, Runtime, and business code fragmentation file packaging. This way, if the project dependencies do not change and the Runtime does not change, the file will not be regenerated each time the package is packaged, only the business code will generate a new file.

Webpack dev – server installation

npm install webpack-dev-server -D
Copy the code

The final webpack.config.js configuration

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

module.exports = {
  mode: 'development'.devtool: 'inline-source-map'.entry: './src/main.js'.output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js'.clean: true,},optimization: {
    runtimeChunk: 'single'.splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors'.chunks: 'all',},},},},devServer: {
    static: './dist'.hot: true,},module: {
    rules: [{test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader'
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader'.'css-loader'] {},test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource'}, {test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource'}},],plugins: [
    new webpack.ProgressPlugin(),
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({ template: './src/index.html'}})]Copy the code

Modify package.json to add the start command to use the automatic refresh function of webpack-dev-server during development

"scripts": {
  "watch": "webpack --watch",
  "start": "webpack serve --open",
  "build": "webpack"
},
Copy the code

Use webpack-dev-server for development

npm start
Copy the code

The browser automatically opens, modifies the code, and the browser automatically refreshes

conclusion

The above is Vue Webpack basic configuration, are the basic configuration, for everyone to better understand and learn the use of Webpack, do not use in the production environment.

Github source: github.com/cmdfas/vue2…