Use webpack (version 4) to build a vue2 project

Before learning webpack, I also searched some blogs that use webpack to build vue projects from the Internet, but when I use it, I will report various problems. The root cause of the error is actually the version problem. The following code has solved many errors. The easiest and most convenient way to build a vue2 project after researching the problem

  1. First create an empty folder
2. Initial configuration
npm init -y(不需要交互,下载更快)
3. Install webpack
npm i [email protected] [email protected] -D
4. Create a configuration file

Manually create a webpack.config.js file in the root directory

Configure the following basic content

const { resolve } = require( 'path'); // node 内置核心模块,用来处理路径问题。
module.exports = {
entry: './src/js/ index .js', // 入口文件
output: { // 输出配置
filename: './built.js', // 输出文件名
path: resolve(__dirname, 'build/js') // 输出文件路径配置
},
mode: 'development' //开发环境
};
5. Download the commonly used loader installation package
npm i [email protected] [email protected] [email protected] [email protected] -D  //打包样式资源
npm install --save-dev [email protected] //打包html资源
npm install --save-dev [email protected] [email protected] [email protected] //打包图片资源
npm i [email protected] -D  //服务器端运行
npm install --save-dev [email protected]  //提取css成单独文件
npm install --save-dev [email protected] [email protected]  //css兼容性处理
npm install --save-dev [email protected] //压缩css
npm install --save-dev clean-webpack-plugin  //清除打包文件
npm i [email protected] [email protected] -D  //安装vue2
npm i [email protected] [email protected] [email protected] 

The above are the more commonly used plug-ins. The usage and precautions of the specific plug-ins are used in ( 5 messages) webpack (4 version) one time

Another way, which is more convenient, is to copy the contents of devDependencies in our package.json, and then use yarn or npm i

 "devDependencies": {
    "clean-webpack-plugin": "^4.0.0",
    "css-loader": "^3.4.2",
    "file-loader": "^5.0.2",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "less": "^3.11.1",
    "less-loader": "^5.0.0",
    "mini-css-extract-plugin": "^0.9.0",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "postcss-loader": "^3.0.0",
    "postcss-preset-env": "^6.7.0",
    "style-loader": "^1.1.3",
    "url-loader": "^3.0.0",
    "webpack-dev-server": "^3.10.3",
   "vue-loader": "^15.7.1",
"vue-template-compiler": "^2.6.10"
  },
 "dependencies": {
    "vue": "^2.6.10",
    "vue-router": "^3.1.3",
    "vue-style-loader": "^4.1.2"
    },
  "browserslist": {
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ],
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  }

After executing the above code, the effect is the same as that of downloading the loader package bit by bit, you can choose to use

6. Configuration file (webpack.config.js)
const { resolve } = require("path"); // node 内置核心模块,用来处理路径问题。

const HtmlWebpackPlugins=require('html-webpack-plugin')
// css分成单独文件
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const {CleanWebpackPlugin}=require('clean-webpack-plugin')
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
const VueLoaderPlugin = require("vue-loader/lib/plugin-webpack4");
process.env.NODE_ENV = 'development'
module.exports = {
    mode: 'development',   // mode=production
  entry: "./src/index.js", // 入口文件
  resolve: {
    extensions: [".js", ".vue", ".json"],
    alias: {
    // 'vue$': 'vue/dist/vue.js',
    "@": resolve(__dirname, "./src"),
    },
    },
  output: {
    // 输出配置
    filename: "./built.js", // 输出文件名
    path: resolve(__dirname, "build"), // 输出文件路径配置
  },
  plugins:[
    new VueLoaderPlugin(),
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugins({
        template: './src/index.html'
    }),
    new MiniCssExtractPlugin({
        filename: './src/css/main.css',
        }),
    new OptimizeCssAssetsWebpackPlugin(),
  ],

  module:{
    rules:[
      {
        test: /\.vue$/,
        loader: "vue-loader",
        },
        {
            test: /\.(c|le)ss$/,
            use: [MiniCssExtractPlugin.loader,
                'css-loader',
                 {
                loader: 'postcss-loader',//预处理,这里指的是在解析css之前,做一下兼容性处理
                options: {
                ident: 'postcss',
                plugins: () => [require('postcss-preset-env')()],
                },
                },
               ],
            },
        {
            test:/\.(jpg|png|jpeg|gif)$/,
            loader: "url-loader",
            options: {
                limit: 6 * 1024,// 最大限制图片
                name: "[name].[hash:10].[ext]", //图片命名+哈希值保留位数+后缀
                outputPath: "images", //导出路径
                esModule: false,  //是否是模块
                },
        },
        {
            //用来解析在html文件中的图片
            test: /\.html$/,
            loader: "html-loader",
            },
     
    ]
  },
  devServer: {
    // 项目构建后路径
    contentBase: resolve(__dirname, 'build'),
    // 启动 gzip 压缩
    compress: true,
    // 端口号
    port: 3000,
    // 自动打开浏览器
    open: true
    }

};

This is my project directory, the routing has not been configured, just built a basic vue project

In this way, the construction of my vue2 project is completed, but if we want the vue project to be displayed in our project, we need to configure some other operations

index.js

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

new Vue({

  render: h => h(App)
}).$mount('#app')

Note the import above, and the path of the import file

index.html

<!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>
    <div id="app">
        
    </div>
</body>
</html>

Note: Be sure to add id='app'

index.view

<template>
    <div>
      哈哈
    </div>
  </template>
  
  <style>

  </style>

The effect of running in the browser

8. Run command

Configure the running command in package.json

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "dev": "webpack-dev-server"
  },

Server-side operation: npm run dev

Packaging command: npm run build

Guess you like

Origin blog.csdn.net/qq_60976312/article/details/129056515