使用Grunt替换文件中的文本 [英] Using Grunt to Replace Text in a File
问题描述
我正在尝试让Grunt替换路径引用,但是我不确定自己做错了什么.这看起来应该可以工作.本质上,我是将Bootstrap文件复制到目录中并更改@import路径,因此我只是尝试用新的目标路径"MY/NEW/DEST/PATH/bootstrap"替换"bootstrap/".我不想像这样直接使用模块,这似乎是不必要的.除了替换之外,一切都正常.
I'm trying to get Grunt to replace a path reference and I'm not sure what I'm doing wrong. This looks like it should work. Essentially, I'm copying a Bootstrap file up a directory and changing the @import paths, so I'm just trying to replace 'bootstrap/' with the new destination path 'MY/NEW/DEST/PATH/bootstrap'. I don't want to use a module for something as straight forward as this, seems needless. Everything works but the replace.
var destFilePath = path.join(basePath, file);
// Does the file already exist?
if (!grunt.file.exists(destFilePath)) {
// Copy Bootstrap source @import file to destination
grunt.file.copy(
// Node API join to keep this cross-platform
path.join(basePath, 'bootstrap/_bootstrap.scss'),
destFilePath
);
// Require node filesystem module, since not a global
var fs = require('fs');
// Replace @import paths to be relative to new destination
fs.readFile(destFilePath, 'utf8', function(err, data) {
// Check for any errs during read
if (err) {
return grunt.log.write(err);
}
var result = data.replace('/bootstrap\//g', 'bootstrap/bootstrap/');
fs.writeFile(destFilePath, result, 'utf8', function(err) {
return grunt.log.write(err);
});
});
}
推荐答案
您将正则表达式用引号引起来-不要这样做,它应该可以正常工作:
You wrapped your regex in quotes - don't do that and it should work fine:
var result = data.replace(/bootstrap\//g, 'bootstrap/bootstrap/');
这篇关于使用Grunt替换文件中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!