博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基于webpack4+vue-cli3项目的换肤功能
阅读量:4509 次
发布时间:2019-06-08

本文共 2221 字,大约阅读时间需要 7 分钟。

起因

最近因公司需求,需要实现主题换肤功能,不仅仅是颜色的更改,还需要包括图片,字体等文件等更换,因此在百度里各种实现方案后,决定根据scss+style-loader/useable做换肤。

项目开始

首先我们用vue-element-admin这个开源的后台管理系统项目来做demo演示,为了便于做二次开发,下载vue-admin-template来开发。

// 从github下载vue-admin-templateclone https://github.com/PanJiaChen/vue-admin-template.gitcd vue-admin-templatenpm installnpm run dev

运行成功后的效果

安装style-loader处理器

因为vue-admin-template项目是添加过sass-loader依赖的,所以不用我们再次安装,在上一步就已经安装好了。

npm install style-loader --save-dev

创建主题文件

  • 在src目录下创建theme-chalk、theme-light主题文件夹
  • 在两个主题目录下创建index.useable.scss文件
  • 在index.useable.scss中写入样式
// theme-chalk/index.useable.scssbody {   background: red; }// theme-light/index.useable.scssbody {   background: green; }

到此,我们的主题样式都已经建好了,现在要将主题应用上去

在vue.config.js中增加style-loader/useable

vue-cli2根vue-cli3的配置区别还是挺大的,我在配置的过程中遇到很多坑,因为vue-cli3没有了webpack.config.js文件,我们在配置webpack的时候无法根据老文档来配置,需要熟悉cli3的webpack-chain来链式修改配置,但是文档很少,配置的过程中异常困难。

在配置文件中chainWebpack链式修改webpack配置就能成功应用loader了,话不多说,直接上代码,

// 换肤loader    const scss = config.module.rule('scss').toConfig();    const useable = { ...scss.oneOf[3], test: /\.useable.scss$/ };    useable.use = [...useable.use];    useable.use[0] = { loader: 'style-loader/useable' };    config.module.rule('scss').merge({ oneOf: [useable] });

使用主题

在准备工作都做好后,接下来我们开始使用主题样式。

之前说的为什么要用style-loader来做换肤呢?是因为style-loader提供了useable这一API,可动态加载删除link文件。具体详情请自行去看看style-loader。

在src目录下,创建theme.js文件

const cache = {};const themeAction = {  chalk() {    if (!cache.chalk) {      cache.chalk = import('./styles/theme-chalk/index.useable.scss');    }    return cache.chalk;  },  light() {    if (!cache.light) {      cache.light = import('./styles/theme-light/index.useable.scss');    }    return cache.light;  }};let current = null;async function setTheme(theme) {  if (themeAction[theme]) {    const style = await themeAction[theme]();    if (current) {      current.unref();    }    style.ref();    current = style;  }}window.setTheme = setTheme;export default setTheme;

在main.js中,引入theme.js。

import setTheme from './theme'// 使用主题setTheme('chalk')

重启服务,查看效果

在实际项目中,可根据传入的主题(chalk/light),动态切换主题色,同时也可根据业务需求,创建多个主题。我们只需要在index.useable.scss文件中写样式变量即可。

转载于:https://www.cnblogs.com/webSciprt/p/ji-yuwebpack4vuecli3xiang-mu-de-huan-fu-gong-neng.html

你可能感兴趣的文章
Linux基础
查看>>
2019北航软工暑期班作业-预培训个人项目(地铁线路规划)
查看>>
【模板】高精度
查看>>
弱弱的玩下Javascript
查看>>
二叉树相关操作
查看>>
在webstorm开发微信小程序之使用阿里自定义字体图标
查看>>
序列化模块/模块/包
查看>>
eclipse maven plugin 插件 安装 和 配置
查看>>
收集一些复杂有用的正则表达式
查看>>
子数组求和之大数溢出
查看>>
浏览器预览office文件(word,Excel,等)
查看>>
MySQL工具汇总
查看>>
cookie
查看>>
如何使用Eclipse编译C,C++,JAVA程序
查看>>
手把手教如何搭建node+egg项目 引入Sequelize
查看>>
Xcode 4 with External Static Library for iPhone Development
查看>>
linux——常用命令清单
查看>>
JS 20180415作业
查看>>
项目追求更高的性能,更高的并发,更高的可用 (1)
查看>>
安卓 okhttp小结
查看>>