样式隔离插件代码postcss-namespace.js如下:
const postcss = require('postcss');
function specailTest(rule) {
if (
rule.parent &&
rule.parent.name &&
rule.parent.name.indexOf('keyframes') > -1
) {
return true
}
return false
}
function classMatchesTest(clss, test) {
if (!test) {
return false
}
clss = clss.trim()
if (test instanceof RegExp) {
return test.exec(clss)
}
if (Array.isArray(test)) {
var tests = test
return tests.some(function(testItem) {
if (testItem instanceof RegExp) {
return testItem.exec(clss)
} else {
return clss === testItem
}
})
}
return clss === test
}
module.exports = postcss.plugin('postcss-namespace', options => {
options = options || {};
const prefix = options.hasOwnProperty('globalName') && options.globalName;
return root => {
if (!prefix || typeof prefix !== 'string') {
return;
}
root.walkRules((rule) => {
if (!rule.selectors) {
return rule;
}
if (specailTest(rule)) {
return rule;
}
rule.selectors = rule.selectors.map((selector) => {
const el = selector.trim();
if (classMatchesTest(selector, options.ignore) || el.length === 0 || el.indexOf(':export') !== -1 || el.match(/^(\s*)(html|body)(\s*)$/)) {
return selector
}
return prefix.trim() + ' ' + selector
})
return rule;
})
};
})
如果是vuecli2脚手架,在build/utils代码调整如下:
// 原代码
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// 现代码
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap,
plugins: [require('./postcss-namespace.js')({globalName:'.subapp-root-app'})]
}
}
调整APP.vue代码,添加当前的这个className:
<template>
<div id="app" class="subapp-root-app">
<router-view/>
</div>
</template>
模板index.html代码调整:
<div id="app" class="subapp-root-app"></div>