手写脚手架(wbepck+vue环境搭建(多页面))

本文详细介绍如何从零开始搭建Vue结合Webpack的开发环境,包括Node.js安装、依赖管理工具Yarn配置、Webpack配置文件详解及Vue项目结构组织等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

wbepck+vue环境搭建

初学,按网上各位大佬的方法自己弄了个脚手架

下一章《webpack+element+vue+express+mangodb+axios显示数据库数据(vue过渡动画)》

node.js下载安装

网上很多自己去查吧,环境配置什么的每个人安装位置不同配置也不同。

命令

由于我公司的网络不好,npm就算用了淘宝镜像也很慢,所以用来yarn

	//淘宝镜像
	npm config set registry https://registry.npm.taobao.org
	yarn config set registry https://registry.npm.taobao.org
	//可以用下面命令查看是否成功
	npm config get registry
	yarn config get registry

建一个新文件夹,在文件夹下输入以下命令:(文件夹路径最好不要有中文,且文件名为项目名)

	//各种插件模块命令,报错缺什么就输入什么命令
	npm init
	npm i yarn -g
	yarn init
	yarn add webpack
	yarn add webpack-cli
	yarn add @babel/core @babel/plugin-transform-runtime @babel/preset-env babel-loader
	yarn add @babel/runtime
	yarn add html-loader html-webpack-plugin
	yarn add node-sass sass-loader css-loader style-loader
	yarn add mini-css-extract-plugin
	yarn add file-loader url-loader
	yarn add webpack-dev-server
	yarn add clean-webpack-plugin
	yarn add compression-webpack-plugin
	yarn add progress-bar-webpack-plugin

目录

目录
目录

代码

webpack.base.js

const path = require('path') ;//path是node.js里的基本包
const HTMLPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');//webpack4配置需要包含VueLoaderPlugin
const ProgressBarPlugin = require('progress-bar-webpack-plugin');

module.exports = {
    context: path.join(__dirname,'../frontend'),
    entry: {
        home1: '../frontend/app.js',
        home2: '../frontend/app2.js',
    },
    output: {
        filename: "[name].[hash].bundle.js",//输出的文件名
        path: path.join(__dirname,'../dist') //输出路径
    },                                        //出口,输出文件
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        }
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: "vue-loader"
            },
            {
                test: /\.js$/,
                use: [{
                    loader: 'babel-loader',
                    options: {
                        presets: ['es2015']
                    }
                }],
                exclude: /node_modules/
            },
            {
                test:/\.(gif|jpg|jpeg|png|svg)$/,
                use:[
                    {
                        loader:'url-loader',
                        options:{
                            limit:1024,
                            name:'[name].[ext]',
                            outputPath: 'static/images',
                            fallback: 'file-loader',
                        }// 图片
                    }
                ]
            }
        ]
    },
    plugins: [
        new VueLoaderPlugin(),
        new HTMLPlugin({
            template:'template.html',// 指定模板html文件
            filename: 'home1.index.html',
            minify:{
                removeRedundantAttributes:true, // 删除多余的属性
                collapseWhitespace:true, // 折叠空白区域
                removeAttributeQuotes: true, // 移除属性的引号
                removeComments: true, // 移除注释
                collapseBooleanAttributes: true // 省略只有 boolean 值的属性值 例如:readonly checked
            },
            chunks: ['home1']
        }),
        new HTMLPlugin({
            template:'template2.html',// 指定模板html文件
            filename: 'home2.index.html',
            minify:{
              removeRedundantAttributes:true, // 删除多余的属性
              collapseWhitespace:true, // 折叠空白区域
              removeAttributeQuotes: true, // 移除属性的引号
              removeComments: true, // 移除注释
              collapseBooleanAttributes: true // 省略只有 boolean 值的属性值 例如:readonly checked
            },
            chunks: ['home2']
        }),
        new ProgressBarPlugin()

    ]
}

webpack.dev.js(开发环境)

const webpackBaseConfig = require('./webpack.base');
const webpack = require('webpack');
const merge = require('webpack-merge');

module.exports = merge(webpackBaseConfig, {
    module: {
        rules: [
        {
            test:/\.css$/,
            use:['style-loader','css-loader'] //css会以js代码出现
        },
        ]
    },
    devServer: {
        port:8000,//端口
        host:'localhost',
        overlay:{//页面可以直接显示错误和警告内容,比较方便
          errors:true,//错误
          warning:true//警告
        },
        open: true,//浏览器直接打开
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),//热替换,修改页面代码后浏览器也跟随变化(实时修改)
    ]
})

webpack.prod.js(生产环境)

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const merge = require('webpack-merge');
const webpackBaseConfig = require('./webpack.base');
const CompressionPlugin = require("compression-webpack-plugin");
const uglify = require('uglifyjs-webpack-plugin');
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const FileManagerPlugin = require('filemanager-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = merge(webpackBaseConfig,{
    module: {
        rules: [{
            test:/\.css$/,
            use:[MiniCssExtractPlugin.loader,'css-loader'] //css会以js代码出现
        }]
    },
    plugins: [
        new CleanWebpackPlugin(),
        new FileManagerPlugin({  //初始化 filemanager-webpack-plugin 插件实例
            onEnd: {
                delete: [   //首先需要删除项目根目录下的dist.zip
                    './dist.zip',
                ],
                archive: [ //然后我们选择dist文件夹将之打包成dist.zip并放在根目录
                    {source: './dist', destination: './dist.zip'},
                ]
            }
        }),
        new CompressionPlugin({//生成gzip
            test: [/\.js$/, /\.css$/],
            filename: '[path].gz',
            algorithm: 'gzip'
        }),
        new MiniCssExtractPlugin({
            filename: 'static/css/[name].[hash].css'//打包生成css文件
        }),
        new OptimizeCSSAssetsPlugin({}),//打包后的css文件中代码压缩
        new uglify()//打包后的代码压缩
    ]
})

template.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>demo</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

App.vue

<template>
    <div id="app">
      <router-view></router-view>//指向路由,app.js中的new vue中的router
    </div>
</template>

<script>
    export default {
      name: 'App',
    }
</script>

<style>
    #app {
        text-align: center;
        margin-top: 150px;
    }
</style>

app.js

import Vue from 'vue'
import App from './App.vue'
import routes from './router'
import VueRouter from "vue-router";

Vue.use(VueRouter)

const router = new VueRouter({ //实例化路由
  //mode: 'history',//这个一定要注释掉,不然app.vue中的<router-view></router-view>无法打包
  routes: routes
});

Vue.config.productionTip = false // 设置为 false 以阻止 vue 在启动时生成生产提示,可以查API文档

console.log("hello world"); //后端输出“hello wrold”,浏览器按F12查看
/* eslint-disable no-new */

let date = ["hello", "world", "this", "is", "es6", "code"]; //同上,用于验证ES6->ES5

((theDate) => {
  theDate.forEach(item => console.log(item));
})(date)

new Vue({
    el: '#app', // id为app的DOM元素,将被挂载(替换)的元素,指向template.html中的div
    router, //指向路由index.js
    components: { App },// 引入组件,这个组件相当于一个大容器,用于承载我们其他的页面,即App.vue
    template: '<App/>'// 将组件包装成这样一个模版,并且将它挂载(替换)到#app这个DOM上
})

index.js

import Home from '../components/home.vue'
import First from '../components/first.vue'
const routes = [ //新版本一定要用routes,不能用routers
  {
    path: '/', //指向home.vue
    name: 'home',
    component: Home,
  },
  {
    path: '/first',//指向first.vue
    name: 'first',
    component: First
  }
];
export default routes //输出routes

first.vue

<template>
  <div id="first">
    <img src="../assets/first.png">
    <p>{{message}}</p>
    <button class="button" @click="goHome">Go Home</button> //跳转到Home.vue
  </div>
</template>

<script>
    export default {
      data () {
        return {
          message: 'This is First!!!'
        }
      },
      methods: {
        goHome: function () {
          this.$router.push({name: 'home'})
        }
      }
      }
</script>

<style scoped>
  p{
    font-size:50px;
    color: #23af1d;
  }
  .button {
    background-color: #419faf;
    border: none;
    color: white;
    padding: 15px 32px;
    display: inline-block;
    font-size: 16px;
  }
</style>

home.vue

<template>
  <div id="home">
    <img src="../assets/home.png">
    <p>{{message}}</p>
    <button class="button" @click="goFirst">Go First</button> //跳转到first.vue
  </div>
</template>

<script>
    export default {
      data () {
        return {
          message: 'This is Home!!!'
        }
      },
      methods: {
        goFirst: function () {
          this.$router.push({name: 'first'})
        }
      }
    }
</script>

<style scoped>
  p{
    font-size:50px;
    color: #23af1d;
  }
  .button {
    background-color: #419faf;
    border: none;
    color: white;
    padding: 15px 32px;
    display: inline-block;
    font-size: 16px;
  }
</style>

App2.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <p>{{message}}</p>
    <button class="button" @click="goHome">Go Home</button>
  </div>
</template>

<script>
    export default {
        name: "App2",
        data () {
          return {
            message: "This is Logo!!!(home2.index.html)"
          }
        },
        methods: {
          goHome: function () {
            window.location.href = "home1.index.html"
          }
        }
    }
</script>

<style scoped>
  #app {
    text-align: center;
    margin-top: 150px;
  }
  p{
    font-size:50px;
    color: #23af1d;
  }
  .button {
    background-color: #419faf;
    border: none;
    color: white;
    padding: 15px 32px;
    display: inline-block;
    font-size: 16px;
  }
</style>

app2.js

import Vue from 'vue'
import App2 from './App2.vue'

Vue.config.productionTip = false;

new Vue({
  el: '#app2', // id为app的DOM元素,将被挂载(替换)的元素
  components: { App2 },// 引入组件,这个组件相当于一个大容器,用于承载我们其他的页面
  template: '<App2/>'// 将组件包装成这样一个模版,并且将它挂载(替换)到#app2这个DOM上
})

template2.js

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>demo2</title>
</head>
<body>
<div id="app2"></div>
</body>
</html>

package.json

{
  "name": "new", //项目名
  "version": "1.0.0", //版本
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config build/webpack.prod.js --mode production", //生产环境(打包)
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.dev.js --open-page home1.index.html", //开发环境
    "server": "node ./mysql/index"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.19.0",
    "babel-core": "^6.26.3",
    "babel-loader": "7",
    "babel-preset-es2015": "^6.24.1",
    "bable-loader": "^0.0.1-security",
    "clean-webpack-plugin": "^3.0.0",
    "compression-webpack-plugin": "^3.0.0",
    "cross-env": "^5.2.0",
    "css-loader": "^3.0.0",
    "file-loader": "^4.0.0",
    "filemanager-webpack-plugin": "^2.0.5",
    "html-webpack-plugin": "^3.2.0",
    "mini-css-extract-plugin": "^0.7.0",
    "mysql": "^2.17.1",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "progress-bar-webpack-plugin": "^1.12.1",
    "style-loader": "^0.23.1",
    "uglifyjs-webpack-plugin": "^2.1.3",
    "url-loader": "^2.0.1",
    "vue": "^2.6.10",
    "vue-loader": "^15.7.0",
    "vue-resource": "^1.5.1",
    "vue-router": "^3.0.7",
    "vue-template-compiler": "^2.6.10",
    "webpack": "^4.35.3",
    "webpack-dev-server": "^3.7.2",
    "webpack-merge": "^4.2.1"
  }
}

.bable

配置文件

{
  "presets": ["es2015"]
}

.editorconfig

编码规范

# 表明这是最顶层的配置文件,这样才会停止继续向上查找 .editorconfig 文件;
# 查找的 .editorconfig 文件是从顶层开始读取的,类似变量作用域的效果,内部
# 的 .editorconfig 文件属性优先级更高
root = true

[*]
# 编码格式。支持latin1、utf-8、utf-8-bom、utf-16be和utf-16le,不建议使用uft-8-bom。
charset = utf-8
# 缩进的类型 [space | tab]
indent_style = space
# 缩进的大小
# tab_width: 设置整数用于指定替代tab的列数。默认值就是indent_size的值,一般无需指定。
indent_size = 2
# 定义换行符 [lf | cr | crlf]
end_of_line = lf
# 文件是否以一个空白行结尾 [true | false]
insert_final_newline = true
# 是否除去换行行首的任意空白字符
trim_trailing_whitespace = true

.gitignore

忽略文件
以”#”号开头表示注释;
以斜杠“/”开头表示目录;
以星号“*”通配多个字符;
以问号“?”通配单个字符
以方括号“[]”包含单个字符的匹配列表;
以叹号“!”表示不忽略(跟踪)匹配到的文件或目录;

.DS_Store
node_modules/ //忽略node_modules文件下所有文件,下同
/dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
/test/unit/coverage/
/test/e2e/reports/
selenium-debug.log

# Editor directories and files
.idea
.vscode
*.suo   //过滤.suo、.ntvs、.njsproj、.sln等文件
*.ntvs*
*.njsproj
*.sln

运行结果

结果截图
home
first
logo

demo

我也是第一次写,初学可能还有许多不懂和错误!
初学建议还是先自动生成脚手架,看完了在自己动手写一遍!
下面是demo,自己下着看吧!
demo:https://github.com/jsq-github/webpack-vue-right-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值