@[TOC](wbepck+vue环境搭建)
# wbepck+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
```
建一个新文件夹,在文件夹下输入以下命令:(文件夹路径最好不要有中文,且文件名为项目名)
```javascript
//各种插件模块命令,报错缺什么就输入什么命令
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
```javascript
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(开发环境)
```javascript
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(生产环境)
```javascript
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
```javascript
<!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
```javascript
<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
```javascript
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
```javascript
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
```javascript
<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
```javascript
<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
```javascript
<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
```javascript
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
```javascript
<!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
```javascript
{
"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
配置文件
```javascript
{
"presets": ["es2015"]
}
```
### .editorconfig
编码规范
```javascript
# 表明这是最顶层的配置文件,这样才会停止继续向上查找 .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
忽略文件
以”#”号开头表示注释;
以斜杠“/”开头表示目录;
以星号“*”通配多个字符;
以问号“?”通配单个字符
以方括号“[]”包含单个字符的匹配列表;
以叹号“!”表示不忽略(跟踪)匹配到的文件或目录;
```javascript
.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
```
## 发布到github
项目目录下右键,选择“git bash here”
输入命令:
```javascript
git init //初始化
```
生成.git文件夹,点击进入,找到config文件添加以下几行内容
```javascript
[user]
email=your email
name=your name
```
接着继续输入命令
```javascript
git add . //添加到仓库,别忘了有一个点
```
```javascript
git commit -m "你要注释的内容" //添加注释
```
登录github,选择star a project
将本地仓库与github仓库关联
ins键可以直接粘贴
```javascript
git remote add origin https://github.com/jsq-github/-.git //关联github仓库
```
```javascript
git push -u origin master //上传
```
第一次中间会跳出来要你输入github的用户名和密码
.gitignore文件作用就是忽略那些不要上传到github
最后大功告成!
## 运行结果
结果截图
## demo
我也是第一次写,初学可能还有许多不懂和错误!
初学建议还是先自动生成脚手架,看完了在自己动手写一遍!
下面是demo,自己下着看吧!
demo:https://github.com/jsq-github/webpack-vue-right-