前端工程化
作为后台人员要适当的理解前端的相应框架,比如Vue+axios,能够基于ElementUI+Vue进行前后端分离项目的搭建。公欲利其事必先利其器,让我们学习点前后端分离,前端需要做些什么?
node.js安装
官网下载Node.js
访问官网: https://nodejs.org/en
安装Node.js
测试安装
Microsoft Windows [版本 10.0.19044.1381]
(c) Microsoft Corporation。保留所有权利。
C:\Users\Administrator>node -v
v18.16.0
配置NPM
npm是什么?
npm,全名 node package manger。
- npm 是
Node
的开放式模块登记和管理系统,是Node.js
包的标准发布平台,用于Node.js
包的发布、传播、依赖控制。 - npm 提供了命令行工具,可以方便地下载、安装、升级、删除包,也可以让你作为开发者发布并维护包。
查看npm配置信息
npm版本号
C:\Users\Administrator>npm -v
9.5.1
npm配置
npm config list -a
; "default" config from default values
_auth = (protected)
access = null
all = false
allow-same-version = false
also = null
audit = true
audit-level = null
auth-type = "web"
before = null
bin-links = true
browser = null
ca = null
; cache = "C:\\Users\\Administrator\\AppData\\Local\\npm-cache" ; overridden by user
cache-max = null
cache-min = 0
cafile = null
call = ""
cert = null
ci-name = null
cidr = null
color = true
commit-hooks = true
depth = null
description = true
dev = false
diff = []
diff-dst-prefix = "b/"
diff-ignore-all-space = false
diff-name-only = false
diff-no-prefix = false
diff-src-prefix = "a/"
diff-text = false
diff-unified = 3
dry-run = false
editor = "C:\\Windows\\notepad.exe"
engine-strict = false
fetch-retries = 2
fetch-retry-factor = 10
fetch-retry-maxtimeout = 60000
fetch-retry-mintimeout = 10000
fetch-timeout = 300000
force = false
foreground-scripts = false
format-package-lock = true
fund = true
git = "git"
git-tag-version = true
global = false
global-style = false
globalconfig = "C:\\Program Files\\nodejs\\node_global\\etc\\npmrc"
heading = "npm"
https-proxy = null
if-present = false
ignore-scripts = false
include = []
include-staged = false
include-workspace-root = false
init-author-email = ""
init-author-name = ""
init-author-url = ""
init-license = "ISC"
init-module = "C:\\Users\\Administrator\\.npm-init.js"
init-version = "1.0.0"
init.author.email = ""
init.author.name = ""
init.author.url = ""
init.license = "ISC"
init.module = "C:\\Users\\Administrator\\.npm-init.js"
init.version = "1.0.0"
install-links = false
install-strategy = "hoisted"
json = false
key = null
legacy-bundling = false
legacy-peer-deps = false
link = false
local-address = null
location = "user"
lockfile-version = null
loglevel = "notice"
logs-dir = null
logs-max = 10
; long = false ; overridden by cli
maxsockets = 15
message = "%s"
metrics-registry = "https://registry.npm.taobao.org/"
node-options = null
noproxy = [""]
offline = false
omit = []
omit-lockfile-registry-resolved = false
only = null
optional = null
otp = null
pack-destination = "."
package = []
package-lock = true
package-lock-only = false
parseable = false
prefer-offline = false
prefer-online = false
; prefix = "C:\\Program Files\\nodejs" ; overridden by user
preid = ""
production = null
progress = true
provenance = false
; proxy = null ; overridden by user
read-only = false
rebuild-bundle = true
; registry = "https://registry.npmjs.org/" ; overridden by user
replace-registry-host = "npmjs"
save = true
save-bundle = false
save-dev = false
save-exact = false
save-optional = false
save-peer = false
save-prefix = "^"
save-prod = false
scope = ""
script-shell = null
searchexclude = ""
searchlimit = 20
searchopts = ""
searchstaleness = 900
shell = "C:\\Windows\\system32\\cmd.exe"
shrinkwrap = true
sign-git-commit = false
sign-git-tag = false
strict-peer-deps = false
strict-ssl = true
tag = "latest"
tag-version-prefix = "v"
timing = false
tmp = "C:\\Users\\ADMINI~1\\AppData\\Local\\Temp"
umask = 0
unicode = false
update-notifier = true
usage = false
user-agent = "npm/{npm-version} node/{node-version} {platform} {arch} workspaces/{workspaces} {ci}"
userconfig = "C:\\Users\\Administrator\\.npmrc"
version = false
versions = false
viewer = "browser"
which = null
workspace = []
workspaces = null
workspaces-update = true
yes = null
; "builtin" config from C:\Program Files\nodejs\node_modules\npm\npmrc
; prefix = "C:\\Users\\Administrator\\AppData\\Roaming\\npm" ; overridden by user
; "user" config from C:\Users\Administrator\.npmrc
cache = "C:\\Program Files\\nodejs\\node_cache"
prefix = "C:\\Program Files\\nodejs\\node_global"
proxy = null
registry = "https://registry.npm.taobao.org/"
; "cli" config from command line options
long = true
配置淘宝镜像(taobao)
D:\vue-workspace\vue-cli>npm install -g cnpm --registry=https://registry.npm.taobao.org
npm WARN deprecated @npmcli/move-file@2.0.1: This functionality has been moved to @npmcli/fs
added 101 packages, removed 27 packages, and changed 469 packages in 20s
C:\Users\Administrator>npm config set registry https://registry.npm.taobao.org
测试配置: npm config ls
【问题】 ‘cnpm’ 不是内部或外部命令,也不是可运行的程序或批处理文件。
在系统环境变量配置PATH: C:\Program Files\nodejs\node_global
C:\Users\Administrator>cnpm -v
cnpm@9.2.0 (C:\Program Files\nodejs\node_global\node_modules\cnpm\lib\parse_argv.js)
npm@9.6.6 (C:\Program Files\nodejs\node_global\node_modules\cnpm\node_modules\npm\index.js)
node@18.16.0 (C:\Program Files\nodejs\node.exe)
npminstall@7.8.0 (C:\Program Files\nodejs\node_global\node_modules\cnpm\node_modules\npminstall\lib\index.js)
prefix=C:\Program Files\nodejs\node_global
win32 x64 10.0.19044
registry=https://registry.npmmirror.com
淘宝镜像过期解决方案
运行npm install -g @vue/cli@4.5.15
npm ERR! code CERT_HAS_EXPIRED
npm ERR! errno CERT_HAS_EXPIRED
npm ERR! request to https://registry.npm.taobao.org/@vue%2fcli failed, reason: certificate has expired
npm ERR! A complete log of this run can be found in: C:\Users\Administrator\AppData\Local\npm-cache\_logs\2024-02-22T00_44_12_317Z-debug-0.log
解决方案
查看镜像
npm config list
D:\wnhz-web>npm config list
; "builtin" config from C:\Users\Administrator\AppData\Roaming\npm\node_modules\npm\npmrc
prefix = "C:\\Users\\Administrator\\AppData\\Roaming\\npm"
; "user" config from C:\Users\Administrator\.npmrc
registry = "https://registry.npm.taobao.org"
; node bin location = C:\Program Files\nodejs\node.exe
; node version = v18.19.0
; npm local prefix = D:\wnhz-web
; npm version = 10.2.3
; cwd = D:\wnhz-web
; HOME = C:\Users\Administrator
; Run `npm config ls -l` to show all defaults.
清空缓存
npm cache clean --force
修改镜像
npm config set registry https://registry.npmmirror.com
解决vscode运行命令行问题
PS C:\Users\Administrator> Get-ExecutionPolicy
Restricted
PS C:\Users\Administrator> Set-ExecutionPolicy RemoteSigned
执行策略更改
执行策略可帮助你防止执行不信任的脚本。更改执行策略可能会产生安全风险,如 https:/go.microsoft.com/fwlink/?LinkID=135170
中的 about_Execution_Policies 帮助主题所述。是否要更改执行策略?
[Y] 是(Y) [A] 全是(A) [N] 否(N) [L] 全否(L) [S] 暂停(S) [?] 帮助 (默认值为“N”): y
PS C:\Users\Administrator>
vue-cli
vue-cli是什么
Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统。Vue CLI 致力于将 Vue 生态中的工具基础标准化。它确保了各种构建工具能够基于智能的默认配置即可平稳衔接,这样你可以专注在撰写应用上,而不必花好几天去纠结配置的问题。
vue-cli安装
使用淘宝镜像安装指定版本
cnpm install -g @vue/cli@4.5.15 --安装指定版本
cnpm install -g @vue/cli – 安装最新版本
C:\Users\Administrator>cnpm install -g @vue/cli@4.5.15
.......
All packages installed (890 packages installed from npm registry, used 46s(network 45s), speed 938.29KB/s, json 787(8.21MB), tarball 32.65MB, manifests cache hit 0, etag hit 0 / miss 0)
[@vue/cli@4.5.15] link C:\Program Files\nodejs\node_global\vue@ -> C:\Program Files\nodejs\node_global\node_modules\@vue\cli\bin\vue.js
最新版安装
D:\vue-workspace\vue-cli\vue-hello>cnpm install -g @vue/cli
Downloading @vue/cli to C:\Program Files\nodejs\node_global\node_modules\@vue\cli_tmp
Copying C:\Program Files\nodejs\node_global\node_modules\@vue\cli_tmp\.store\@vue+cli@5.0.8\node_modules\@vue\cli to C:\Program Files\nodejs\node_global\node_modules\@vue\cli
......
@graphql-tools/merge@^8.4.1(8.4.2) (18:06:05)
Run 2 script(s) in 186ms.
All packages installed (770 packages installed from npm registry, used 37s(network 37s), speed 593.57KB/s, json 37(1.76MB), tarball 19.51MB, manifests cache hit 635, etag hit 635 / miss 8)
[@vue/cli@5.0.8] link C:\Program Files\nodejs\node_global\vue@ -> C:\Program Files\nodejs\node_global\node_modules\@vue\cli\bin\vue.js
检查版本号
D:\vue-workspace\vue-cli\vue-hello>vue --version
@vue/cli 4.5.15
或者
D:\vue-workspace\vue-cli\vue-hello>vue --version
@vue/cli 5.0.8
创建vue-cli项目
D:\vue-workspace\vue-cli\vue-hello>vue create hello-world
选择Vue的版本号
Vue CLI v5.0.8
? Please pick a preset:
Default ([Vue 3] babel, eslint)
Default ([Vue 2] babel, eslint)
Manually select features
创建项目(自动安装)
D:\vue-workspace\vue-cli>vue create hello-world
Vue CLI v5.0.8
? Please pick a preset: Default ([Vue 2] babel, eslint)
Vue CLI v5.0.8
✨ Creating project in D:\vue-workspace\vue-cli\hello-world.
🗃 Initializing git repository...
⚙️ Installing CLI plugins. This might take a while...
added 856 packages in 39s
🚀 Invoking generators...
📦 Installing additional dependencies...
added 92 packages in 7s
⚓ Running completion hooks...
📄 Generating README.md...
🎉 Successfully created project hello-world.
👉 Get started with the following commands:
$ cd hello-world
$ npm run serve
创建项目(手动安装)
运行服务
修改前端项目启动端口号
-
在项目根目录下创建vue.config.js文件
-
编辑vue.config.js文件
module.exports={ devServer:{ port: 33333 } }
-
测试
Vue项目结构
配置服务端口
如果修改启动的服务端口,可以修改vue.config.js文件
module.exports ={
devServer:{
open:true,
port:8099
}
}
main.js
src/main.js是入口文件,主要作用是初始化vue实例并使用需要的插件
在main.js文件中定义了一个vue对象,其中el为实例提供挂载元素
package.json
{
"name": "hello-worldx", //项目名称
"version": "0.1.0", //项目包版本 「主版本号. 次版本号. 修订号」
"private": true, //防止我们意外地将私有库发布到 npm 服务器。
"scripts": { //scripts 是 package.json 中内置的脚本入口
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"dependencies": { //生产环境中所必须的依赖包,将来可以通过这里的配置 下载依赖 dependencies :参与编译和打包
"core-js": "^3.8.3",
"register-service-worker": "^1.7.2",
"vue": "^2.6.14"
},
"devDependencies": { //开发阶段需要的依赖包,不参与打包
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-pwa": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"less": "^4.0.0",
"less-loader": "^8.0.0",
"vue-template-compiler": "^2.6.14"
},
"browserslist": [ //告知支持哪些浏览器及版本。
"> 1%",
"last 2 versions",
"not dead"
]
}
关闭多单词检查
- 关闭组件命名多单词检查(vue/multi-word-component-name)
- 关闭不使用变量检查(no-unused-vars)
"rules": {
"vue/multi-word-component-names":"off",
"no-unused-vars":"off"
}
【bug】运行时报错处理
有时候运行 npm run serve时会报以下错误
Error: error:0308010C:digital envelope routines::unsupported
解决方案,在package.json中添加如下代码
"scripts": {
"serve": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
"build": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build"
},
elementUI
添加element-ui依赖
npm i element-ui -S
出现警告:WARN deprecated core-js@2.6.12: core-js@❤️.23.3 is no longer maintained and not recommended for usage due to the number of issues.
解决方案: 需升级core-js到3版本以上
npm i core-js
在main.js中添加elementui
import Vue from 'vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css'
import App from './App.vue'
Vue.config.productionTip = false
import router from './router'
Vue.use(router)
Vue.use(ElementUI)
new Vue({
render: h => h(App),
router,
}).$mount('#app')
在组件中使用elementui
以Welcome组件为例:
<template>
<el-table
:data="tableData"
style="width: 100%">
<el-table-column
prop="date"
label="日期"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="姓名"
width="180">
</el-table-column>
<el-table-column
prop="address"
label="地址">
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [{
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}, {
date: '2016-05-04',
name: '王小虎',
address: '上海市普陀区金沙江路 1517 弄'
}, {
date: '2016-05-01',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
}, {
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1516 弄'
}]
}
}
}
</script>
项目中引用字体
引入字体
在assert中创建font文件,并拷贝字体到此文件夹。
编辑css文件
在font中场景font.css 文件,并编辑字体。
@font-face {
/* 自定义的字体名字,调用该字体时使用 */
font-family: "newFont";
/* 引用字体包 */
src: url('书体坊颜体.ttf');
font-weight: normal;
font-style: normal;
}
main.js配置全局
import Vue from 'vue'
import App from './App.vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css'
import '@/assets/font/font.css' //引入字体
Vue.use(ElementUI)
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount('#app')