我现在通过 JavaScript 运行 Less,使用 less = { env: 'development' };
,我有一个名为 main.less 的主文件,其中包含我所有的 @import
,但是我导入的“子”.less 文件都没有更新,而且似乎只是在使用旧的缓存样式。
将一行代码放入main.less,编译。删除它并放入 nav.less,编译 main.less,然后似乎从缓存中提取 nav.less。呃。
我试过 less.refresh();
,甚至试过 localStorage.clear();
,但结果似乎没有任何改变。
我被这件事打败了。
最佳答案
你说 localStorage.clear() 所以你必须在浏览器中使用 less 。我试图为此构建一个环境,并且一切都按预期工作。我使用了 less 选项,如下所示:
{
filename: "./test/main.less",
useFileCache: false
}
html文件如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>test page</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="blackmiaool's page">
<meta name="author" content="blackmiaool">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="js/less.min.js"></script>
<script src="js/jquery-2.1.3.js"></script>
</head>
<body>
<button id="next">Next</button>
<textarea id="output" placeholder="output" style="height:230px;width:230px;">
</textarea>
<script type="text/javascript">
console.log(less);
function update() {
$.get("./test/main.less", function(mainFileContent) {
less.render(mainFileContent, {
filename: "./test/main.less",
useFileCache: false
})
.then(function(output) {
$("#output").val(output.css);
console.log(output);
})
});
}
update();
$("#next").on("click", update);
</script>
</body>
main.less:
@import "./nav.less";
h5 {
font-size: 20px;
color: aliceblue;
}
无导航:
h4 {
font-size: 50px;
}
你可以在这里下载一个演示(你应该自己部署它):http://blackmiaool.com/test_less_demo.zip
我是如何重现问题的
- 打开页面
- 打开main.less
- 删除行
color: aliceblue;
- 保存main.less
- 打开nav.less
- 将行
color: aliceblue;
插入第二行。 - 保存 nav.less
- 点击“下一步”按钮
输出从
h4 {
font-size: 50px;
}
h5 {
font-size: 20px;
color: aliceblue;
}
到
h4 {
font-size: 50px;
color: aliceblue;
}
h5 {
font-size: 20px;
}
如果文件请求被缓存了怎么办?
Less的文件请求码(来自less):
FileManager.prototype.doXHR = function doXHR(url, type, callback, errback) {
var xhr = new XMLHttpRequest();
var async = options.isFileProtocol ? options.fileAsync : true;
if (typeof xhr.overrideMimeType === 'function') {
xhr.overrideMimeType('text/css');
}
logger.debug("XHR: Getting '" + url + "'");
xhr.open('GET', url, async);
根据这个片段,less 使用 xhr
来获取文件(当然)。所以我们可以尝试破解 XMLHttpRequest
来更改 url:
var preOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
var args = Array.prototype.slice.call(arguments, 0);
if (url.match(/\.less$/)) {
url += `?time=${Date.now()}`;
args[1]=url;
}
return preOpen.apply(this, args);
}
然后打开“网络”选项卡查看较少的文件请求。
关于javascript - Less.js 主动缓存导入的 LESS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38258112/