1.开发环境 webpack+vue

2.电脑系统 windows11专业版

3.初始化项目:

yarn init -y

or 

npm init-y

4.安装webpck webpack-cli

yarn add webpack@4.46.0 webpack-cli@3.3.12 -D

5.安装vue

yarn add vue@2.6.14 -S

6.新建src文件夹(和node_modules同级)

//在src文件夹新建main.js和App.vue

6-1.App.vue代码如下:

<template>
  <div id="app"></div>
</template>

<script>
export default {
  name: "App.vue"
}
</script>

<style scoped>

</style>

6-2.main.js代码如下:

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

new Vue({
    el:'#app',
    render:h=>h(App)
})

7.新建public文件夹(和node_modules同级)

在public 文件夹下新建 index.html

7-1.index.html代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chen-webpack</title>
</head>
<body>

</body>
</html>

8.在根目录新建webpack.config.js(和package.json同级)

const path = require('path');
module.exports = {
    entry: './src/main.js',//入口
    output:{
        filename:'[name].js',//出口文件名
        path:path.resolve(__dirname,'dist'),//出口路径
    },
    mode:'development',
}
yarn webpack

image.png

image.png

//简单的配置,打包成功了,但是由报错,是因为我们使用了
vue但是没有进行配置,而且我们打包之后的文件没有html文件,
我们需要把public中的index.html打包到dist目录

image.png

9.安装html-webpack-plugin

yarn add html-webpack-plugin@4.5.2 -D
//在webpack.config.js中添加如下代码
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    plugins:[
        new HtmlWebpackPlugin({
            template:path.resolve(__dirname,'public/index.html')
        })
    ]
}
yarn webpack

image.png

//在webpack.config.js中添加 chunkhash

output:{
    filename:'[name]_[chunkhash].js',//出口文件名
    path:path.resolve(__dirname,'dist'),//出口路径
},

image.png

//之前的文件还是存在,那我们能不能在每次打包的时候都删除冗余的文件呢?

10.安装clean-webpack-plugin

yarn add clean-webpack-plugin -D
//在webpack.config.js中添加如下代码
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
module.exports = {
    plugins: [
        new CleanWebpackPlugin()
    ]
}
yarn webpack

image.png

image.png

11.安装vue-loader vue-template-compiler

yarn add vue-loader@15.9.8 vue-template-compiler -D
//在webpack.config.js中添加如下代码

const VueLoaderPlugin = require('vue-loader/lib/plugin');
// const {VueLoaderPlugin} = require('vue-loader');
module.exports = {
    module: {
        rules: [
            {
                test: /\.vue$/, use: 'vue-loader'
            }
        ]
    },
    plugins: [
        new VueLoaderPlugin(),
    ]
}

image.png

image.png

//之前的报错没有了

12.安装vue路由

yarn add vue-router@3.5.3 -S

12-1.在src下新建views文件夹,在views文件夹下新建文件夹About文件夹--->About.vue和Home文件夹--->Home.vue

目录结构如下:

image.png
12-2.Home--->Home.vue代码如下:

<template>
  <div>我是Home页面</div>
</template>

<script>
export default {
  name: "Home"
}
</script>

<style scoped>

</style>

12-3.About--->About.vue代码如下:

<template>
  <div>我是About页面</div>
</template>

<script>
export default {
  name: "About"
}
</script>

<style scoped>

</style>

12-4.在src新建router--->index.js

import Vue from "vue";
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        name: "Home",
        component: () => import(/* webpackChunkName:"Home" */ "../views/Home/Home.vue")
    },
    {
        path: '/About',
        name: "About",
        component: () => import(/* webpackChunkName:"About" */ "../views/About/About.vue")
    }
]

const router = new VueRouter({
    routes,
});

export default router;

12-5.在main.js中进行引入:

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


new Vue({
    el:'#app',
    router,
    render:h=>h(App)
})

12-6.在App.vue中添加代码:

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: "App.vue"
}
</script>

<style scoped>

</style>

13.现在可以启动项目了,安装webpack-dev-server来启动项目:

yarn add webpack-dev-server@3.11.3 -D

13-1.在package.json中添加如下代码:

"scripts": {
  "dev": "webpack-dev-server --open",
  "build": "webpack --config webpack.config.js"
},

13-2.先打包,yarn build
image.png

image.png

13-3.启动项目,yarn dev

// Home页面

image.png

// About页面

image.png

14.使用css扩展语言:less

// 安装less less-loader css-loader style-loader

yarn add less@3.9.0 less-loader@5.0.0 css-loader@4.3.0 style-loader@2.0.0 -D

14-1.在About--->About.less

.About{
  width: 100%;
  height: 300px;
  background-color: pink;
  .About-top{
    width: 100px;
    height: 100px;
    background-color: darkcyan;
  }
}

14-2.在About-->About.vue中引入

  <div class="About">
    我是about页面
    <div class="About-top">
      我是about上部分
    </div>
  </div>
</template>

<script>
export default {
  name: "About"
}
</script>

<style lang="less" scoped>
@import "./About.less";
</style>

14-3.在webpack.config.js中添加如下代码:

module.exports = {
    module: {
        rules: [
            {
                test: /\.less$/, use: [{
                    loader: 'style-loader' // creates style nodes from JS strings
                }, {
                    loader: 'css-loader' // translates CSS into CommonJS
                }, {
                    loader: 'less-loader' // compiles Less to CSS
                }]
            }
        ]
    },
}

14-4.运行项目 yarn dev
image.png

15.抽离css,安装插件mini-css-extract-plugin

yarn add mini-css-extract-plugin@1.6.2 -D
//在webpack.config.js中添加如下代码

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    module: {
        rules: [
            {
                test: /\.less$/, use: [{
                    loader: MiniCssExtractPlugin.loader,
                    options: {
                        publicPath: path.resolve(__dirname, 'dist/style')
                    }
                }, {
                    loader: 'css-loader' // translates CSS into CommonJS
                }, {
                    loader: 'less-loader' // compiles Less to CSS
                }]
            },
            {
                test: /\.css$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: path.resolve(__dirname, 'dist/style')
                        }
                    },
                    "css-loader"
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "style/[name].css",
        }),
    ]
}
yarn build

image.png

image.png

less语言已经被转换为css了

16.把>=es6语法转es5,使用babel-loader:

// 
/*
* babel-loader
* @babel/core :babel核心库
* @babel/preset-env : 把js高级语言转es5
* */
 
yarn add babel-loader @babel/core @babel/preset-env -D 
//在webpack.config.js中添加如下代码

module.exports = {
    module: {
        rules: [
            {
                test: /\.m?js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            }
        ]
    },
}
//修改 About--->About.vue代码
<template>
  <div class="About">
    我是about页面
    <div class="About-top">
      我是about上部分
    </div>
  </div>
</template>

<script>
export default {
  name: "About",
  data() {
    return {
      AboutList: [
        {id: 1, name: "张三"},
        {id: 2, name: "李四"},
        {id: 3, name: "王五"}
      ]
    }
  },
  mounted() {
    const [AboutCon1,AboutCon2, AboutCon3] = this.AboutList;
    console.log(AboutCon1);
    console.log(AboutCon2);
    console.log(AboutCon3);
  }

}
</script>

<style lang="less" scoped>
@import "./About.less";
</style>
// es6 结构赋值
//yarn dev

image.png

yarn build

image.png

//之前使用 const声明的变量,在这里变成了var;表示es6语言转换成了es5

17.如何配置网站图标呢?
image.png

17-1.在webpack.config.js中添加如下代码

module.exports = {
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, 'public/index.html'),
            favicon: path.resolve(__dirname, 'public/logo.ico')
        }),
    ]
}
//yarn dev

image.png

18.postcss--->是一个用JavaScript工具和插件转换css代码的工具,比如可以使用autoprefixer插件自动获取浏览器的流行度和能够支持的属性,并根据这些数据帮助我们自动的为css规则添加前缀,将最新的css语法抓换成大多数浏览器都能理解的语法。

//安装
yarn add postcss-loader@4.3.0 autoprefixer@9.5.1 -D

18-1.在根目录下新建postcss.config.js(和package.json同级):

module.exports = {
    plugins: [
        require('autoprefixer')
    ]
}

18-2.在webpack.config.js中添加如下代码

module.exports = {
    module: {
        rules: [
            {
                test: /\.(css|less)$/,
                exclude: path.resolve(__dirname, "node_modules"),
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: path.resolve(__dirname, 'dist/style')
                        }
                    },
                    {
                        loader: 'css-loader' // translates CSS into CommonJS
                    },
                    {
                        loader: 'postcss-loader'
                    },
                    {
                        loader: 'less-loader'
                    }
                ]
            },
            }
        ]
    },
}

18-3.在package.json中添加如下代码:

"browserslist": [
    "iOS >=6",
    "Android > 4",
    "Safari >= 6",
    "last 3 iOS versions",
    "last 3 Safari versions",
    "last 10 Chrome versions",
    "last 5 Firefox versions",
    "last 2 versions",
    "> 1%",
    "maintained node versions",
    "not dead"
  ]

18-4.Home--->Home.less

.Home{
    width: 100%;
    height: 100px;
    background-color: cadetblue;
    display: flex;
}
//在Home.vue中引入:
<style scoped>
@import "Home.less";
</style>

18-5.yarn dev
image.png

18-6.yarn build
image.png

18-7.优化postcss和autoprefixer配置,上面的autoprefixer配置只有webkit前缀,修改webpack.config.js和postcss.config.js配置

// webpack.config.js
module.exports = {
    module: {
        rules: [
            {
                test: /\.(css|less)$/,
                exclude: path.resolve(__dirname, "node_modules"),
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: path.resolve(__dirname, 'dist/style')
                        }
                    },
                    {
                        loader: 'css-loader', // translates CSS into CommonJS
                    },
                    {
                        loader: 'postcss-loader'
                    },
                    {
                        loader: 'less-loader'
                    },

                ]
            },
        ]
    },
}
// postcss.config.js
module.exports = {
    plugins: [
        require('autoprefixer')(
            {
                browsers: [
                    "> 1%",
                    "iOS >=6",
                    "Android > 4",
                    "last 3 iOS versions",
                    "last 100 Safari versions",
                    "last 100 Chrome versions",
                    "last 100 Firefox versions",
                    "last 100 Opera versions",
                    "last 100 versions",
                    "maintained node versions",
                    "not dead"
                ]
            }
        )
    ]
}
//删除 package.json中的browserslist
yarn build

image.png

19.如何实现多页面呢?
image.png

webpack的官网是这样实现的,这样是可以的,但是呢?怎么如果有很多了页面,我需要手动去一个一个的添加,

module.exports = {
  entry: {
    pageOne: './src/pageOne/index.js',
    pageTwo: './src/pageTwo/index.js',
    pageThree: './src/pageThree/index.js',
    ......
  }
};

//项目小的话,这样一个一个的添加还可以,但是项目很大的话,这样就不合适了,我们可以使用动态入口来解决这个问题,怎么实现动态入口呢?如下:

19-1.动态入口--->entry:

//安装 glob库
yarn add glob@7.2.0 -D
//覆盖 webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
// const VueLoaderPlugin = require('vue-loader/lib/plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const {VueLoaderPlugin} = require('vue-loader');
const glob = require('glob') // 遍历目录

const entryFiles = glob.sync(path.join(__dirname, "./src/views/*/index.html"));

const htmlwebpackplugins = [];
entryFiles.map((item, index) => {
    const entryFile = entryFiles[index];
    // // console.log(entryFile);
    const match = entryFile.match(/src\/views\/(.*)\/index\.html$/);
    // // console.log(match);
    const pageName = match[1];
    htmlwebpackplugins.push(
        new HtmlWebpackPlugin({
            template: `./src/views/${pageName}/index.html`,
            filename: `${pageName}/index.html`,
            chunks: [`${pageName}`], //表示:只会把这个chunk的信息添加到这段html中
            inject:"body",
            favicon: path.resolve(__dirname, './src/views/Index/logo.ico'),
        })
    );
});

const entryFilesJs = glob.sync(path.join(__dirname, "./src/views/*/main.js"));

const Entrys ={};
entryFilesJs.map((item, index) => {
    const entryFileJs = entryFilesJs[index];
    // console.log(entryFileJs);
    const match = entryFileJs.match(/src\/views\/(.*)\/main\.js$/);
    // console.log(match);
    const pageNameJs = match[1];
    Entrys[pageNameJs] = entryFileJs;
});

module.exports = {
    entry: {...Entrys,Index:'./src/main.js'},//入口
    output: {
        filename: '[name]/[name].js',//出口文件名
        path: path.resolve(__dirname, 'dist'),//出口路径
        chunkFilename: '[name]/[name].js',
    },
    mode: 'development',//模式
    resolve: {
        alias: {
            '@@': path.resolve(__dirname, './src'),
            "ActivityThreeAdminComponents": path.resolve(__dirname, './src/views/activityThreeAdmin/src/components'),
            "ShortVideoAdminComponents": path.resolve(__dirname, './src/views/ShortVideoAdmin/src/components'),
        }
    },
    module: {
        rules: [
            {
                test: /\.vue$/, use: 'vue-loader'
            },
            {
                test: /\.(css|less)$/,
                exclude: path.resolve(__dirname, "node_modules"),
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                    },
                    {
                        loader: 'css-loader', // translates CSS into CommonJS
                    },
                    {
                        loader: 'postcss-loader'
                    },
                    {
                        loader: 'less-loader'
                    },

                ]
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            }
        ]
    },
    plugins: [
        new VueLoaderPlugin(),
        ...htmlwebpackplugins,
        new MiniCssExtractPlugin({
            filename: "[name]/[name].css",
        }),
        new CleanWebpackPlugin(),
    ]
}

19-2.在src/views新建文件夹--->结构如下:
image.png

image.png

19-3.src--->router--->index.js

import Vue from "vue";
import VueRouter from 'vue-router';
import Index from "@@/views/Index/Index.vue";
import About from "ActivityThreeAdminComponents/About.vue";
import Home from "ShortVideoAdminComponents/Home.vue";
Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        name: "Index",
        component:Index
    },
    {
        path: '/ActivityThreeAdmin',
        name: "ActivityThreeAdmin",
        component:About
    },
    {
        path: '/ShortVideoAdmin',
        name: "ShortVideoAdmin",
        component: Home
    }
]

const router = new VueRouter({
    routes,
});

export default router;

19-4.具体代码举例:ShortVideoAdmin

// index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ShortVideoAdmin管理</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
// main.js
import Vue from 'vue';
import App from './App.vue';
import router from './src/router'


new Vue({
    el:'#app',
    router,
    render:h=>h(App)
})
// App.vue
<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: "App.vue"
}
</script>

<style scoped>

</style>
// Add.vue
<template>
<div class="Add">
  我是短视频管理新建页面
</div>
</template>

<script>
export default {
  name: "Add"
}
</script>

<style scoped>

</style>
// Home.vue
<template>
  <div class="Home">我是短视频管理</div>
</template>

<script>
export default {
  name: "Home"
}
</script>

<style scoped>
.Home{
  width: 100%;
  height: 100px;
  background-color: cadetblue;
  display: flex;
  transform: translate(20px,20px);
  font-size: 30px;
}
</style>
// router.js
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../components/Home.vue";
import Add from "../components/Add.vue";

Vue.use(VueRouter);

const routes = [
    {
        path: "/",
        name: "Home",
        component: Home,
    },
    {
        path: "/add",
        name: "Add",
        component: Add,
    },
]

const router=new VueRouter({
    routes
})
export default router;

19-5.把public中的index.html和logo.ico复制到Index文件夹下,然后删除public文件夹
image.png

20.yarn build
image.png

image.png

image.png

image.png

//这样就实现了多页面管理

10000.本期的分享到了这里就结束啦,希望对你有所啊帮助,让我们一起努力走向巅峰!


灰太狼的情与殇
51 声望2 粉丝

某,从来都不相信所谓的天赋和天才,只有不断努力的平凡人。只要内心是坚定的,就会有所收获;失败会让我们成长,让我们一起努力走向巅峰。