本篇文章给大家分享的是有关怎么在vue-cli3项目中使用webpack4实现换肤功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
首先我们用vue-element-admin
这个开源的后台管理系统项目来做demo演示,为了便于做二次开发,下载vue-admin-template来开发。
// 从github下载vue-admin-template
clone https://github.com/PanJiaChen/vue-admin-template.git
cd vue-admin-template
npm install
npm 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.scss
body {
background: red;
}
// theme-light/index.useable.scss
body {
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')
重启服务,查看效果
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
以上就是怎么在vue-cli3项目中使用webpack4实现换肤功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。