Webpack 搭建 Vue.js 项目并进行不同PC端屏幕适配配置中文标题
Posted 魏晓蕾
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Webpack 搭建 Vue.js 项目并进行不同PC端屏幕适配配置中文标题相关的知识,希望对你有一定的参考价值。
1、Webpack 搭建 Vue.js 项目
- 安装 node 环境
node.js 官网下载地址:https://nodejs.org/zh-cn/ - 安装 Vue
npm install vue
- 安装 vue-cli
npm install --global vue-cli
- 安装 vue/cli-init
npm install --global @vue/cli-init
不安装 vue/cli-init 执行 vue init webpack webpack-vue-demo 创建 webpack 项目,报错如下:
Command vue init requires a global addon to be installed.
Please run yarn global add @vue/cli-init
- 安装 webpack
npm install --global webpack
- 安装 webpack-dev-server
npm install --global webpack-dev-server
- Webpack 搭建 Vue.js 项目
vue init webpack webpack-vue-demo
- 运行 vue 项目
cd webpack-vue-demo
npm run dev
- 浏览器访问:http://localhost:8080,即可打开搭建的 Vue.js 项目。
- 项目目录结构如下:
2、不同 PC 端屏幕适配
- 安装 lib-flexible
npm install lib-flexible --save
- 安装 px2rem-loader
npm install px2rem-loader --save
- 在项目入口文件 main.js 中引入 lib-flexible
import 'lib-flexible'
- 在 build/utils.js 中添加如下代码:
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const px2remLoader = { // 添加的代码
loader: 'px2rem-loader',
options: {
remUnit: 60
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
- 将 px2remLoader 放入 loaders 数组中
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader, px2remLoader] : [cssLoader, px2remLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
- 重启项目:
npm run dev
3、解决 webpack-dev-server 无法自动编译热更新
- WebStorm 中关闭 safe write(安全写入)功能:
4、配置中文标题
如果项目每个页面的标题不同,在 router/index.js 中配置:
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/Login'
import Index from '@/views/Index'
import {notification} from "ant-design-vue";
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
redirect: '/index'
},
{
path: '/login',
name: 'Login',
component: Login,
meta: {
title: '登录'
}
},
{
path: '/index',
name: 'Index',
component: Index,
meta: {
title: '首页'
}
}
]
})
router.beforeEach((to, from, next) => {
if (to.meta.title) {
document.title = to.meta.title
}
if (to.path == '/login' || localStorage.getItem("token")) {
next()
} else {
notification.open({
message: '登录提示',
description: '您还未登录或Token已过期,请重新登录'
})
return next("/login")
}
})
export default router
如果项目每个页面的标题都相同,则在项目入口页面 index.html 中设置 title 为项目标题:
## index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>信息管理平台</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
5、代码示例
## module1.js
import module2 from "./module2.js"
export default {
f1: function () {
console.log(1);
},
obj: {
a: 123,
b: mode2
}
}
## module2.js
export default 4554;
## module3.js
/*export function f2() {
console.log('f2')
}
export function f3() {
console.log('f3')
}
export function f4() {
console.log('f4')
}*/
function class1() {
}
class1.prototype.f2 = function () {
console.log('f2')
}
class1.prototype.f3 = function () {
console.log('f3')
}
class1.prototype.f4 = function () {
console.log('f4')
}
module.exports = class1
## app.js
import mode1 from "./module/mode1.js"
import class1 from "./module/module3.js"
import $ from "jquery";
import icon from "./img/icon.png"
import d from "./img/d.png"
import ewm from "./img/ewm.jpg"
$.extend({ a: 1 })
var iconImage = new Image();
iconImage.src = icon
var dImage = new Image();
dImage.src = d
var ewmImage = new Image();
ewmImage.src = ewm
class1.f2();
import "./css/test.css"
import "./css/test1.less"
const a = 444;
var b = 999;
console.log(a);
setInterval(() => {
console.log(b++)
}, 500)
mode1.f1();
console.log(mode1.obj.b)
## app2.js
import mode1 from "./module/mode1.js"
import _ from "lodash"
_.add(123, 10);
mode1.f1();
console.log(mode1.obj.b)
## package.json
{
"name": "code",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \\"Error:a no test specified\\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.14.6",
"@babel/preset-env": "^7.14.7",
"babel-loader": "^8.2.2",
"css-loader": "^6.1.0",
"css-minimizer-webpack-plugin": "^3.0.2",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"image-webpack-loader": "^7.0.1",
"imagemin": "^8.0.0",
"imagemin-gifsicle": "^7.0.0",
"imagemin-mozjpeg": "^9.0.0",
"imagemin-pngquant": "^9.0.2",
"img-loader": "^4.0.0",
"jquery": "^3.6.0",
"less": "^4.1.1",
"less-loader": "^10.0.1",
"lodash": "^4.17.21",
"mini-css-extract-plugin": "^2.1.0",
"style-loader": "^3.1.0",
"url-loader": "^4.1.1",
"webpack": "^5.45.1",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"devDependencies": {
"extract-text-webpack-plugin": "^4.0.0-beta.0"
}
}
## webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const cssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
// optimize-css-assets-webpack-plugin 旧版webpack使用的CSS压缩工具
module.exports = {
mode: "development",
entry: {
app: "./app.js",
app2: "./app2.js"
},
optimization: {
splitChunks: {
// async表示只从异步加载得模块(动态加载import())里面进行拆分,initial表示只从入口模块进行拆分,all表示以上两者都包括
chunks: 'all',
minSize: 0,
cacheGroups: {
vendors: {
test: /[\\\\/]node_modules[\\\\/]/,
priority: -10
}
}
}
},
output: {
path: __dirname + "/dist/",
filename: "[name].js"
},
devServer: {
port: 3000,
hot: true,
hotOnly: true,
proxy: {
'/api': 'http://localhost:3000',
},
/*proxy: {
'/api': {
target: 'http://localhost:3000',
pathRewrite: { '^/api': '' },
},
},*/
},
module: {
rules: [
/* {
test: /\\.css$/,
use: extractPlugin.extract(
{
fallback: {
loader: "style-loader"
},
use: [
{
loader: "css-loader"
}
]
}
)
}*/
{
test: /\\.js$/,
use: [{
loader: "babel-loader",
options: {
presets: [
[
"@babel/preset-env", {
targets: {
browsers: [">1%", "ie>=7"]
}
}
]
],
plugins: []
}
}]
},
{
test: /\\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
{
test: /\\.less$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"less-loader"
]
},
{
test: /\\.(jpg|png|jpeg|gif)$/,
use: [{
loader: 'url-loader',
options: {
limit: 5000,
name: '[name]-[hash:10].[ext]',
}
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
quality: 65
},
pngquant: {
speed: 4
},
}
},
{
loader: "img-loader",
options: {
plugins: [
require("imagemin-pngquant")({
// 压缩 png 插件,取值范围 1-11,值越大压缩率越小,值越小压缩生成的文件越小,默认为4
speed: 4,
}),
require("imagemin-mozjpeg")({
// 压缩 jpg 插件,取值范围1-100,值越大压缩率越小,值越小压缩生成的文件越小
quality: 50,
}),
],
},
},
]
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "test.css"
}),
new HtmlWebpackPlugin({
template: "./index.html",
filename: "index.html",
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
}
}),
new webpack.DllReferencePlugin({
manifest: require("./dll/vendor-manifest.json")
}),
]
}
## webpack.dll.js
const webpack = require('webpack');
module.exports = {
entry: {
vendor: ['jquery', 'lodash'],
},
output: {
path: __dirname + "/dll",
filename: '[name].dll.js',
library: '[name]_library'
},
plugins: [
new webpack.DllPlugin({
path: __dirname + "/dll/[name]-manifest.json",
name: '[name]_library'
})
]
}
以上是关于Webpack 搭建 Vue.js 项目并进行不同PC端屏幕适配配置中文标题的主要内容,如果未能解决你的问题,请参考以下文章