[英]How remove white space from template literals when stored in an object?
I'm creating a boilerplate project with node.我正在使用节点创建一个样板项目。
At its most basic when I run node create.js projectName
I want to create a project folder with a bunch of assets.在最基本的情况下,当我运行
node create.js projectName
时,我想创建一个包含一堆资产的项目文件夹。
This is a snippet of the code:这是代码片段:
function data(){
return {
'index.html': `<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" media="screen" href="css/main.css" />
...
<body> <script src="myscripts/main.js"></script> </body>
</html>`,
}
}
Then I create the file然后我创建文件
fs.writeFileSync(`${p[0]}/index.html`, data()['index.html'])
I removed a lot of irrelevant code but, the point in the generated index.html
looks like this我删除了很多不相关的代码,但是生成的
index.html
中的点看起来像这样
<!DOCTYPE html>
<html lang="en">
...
<body> <script src="myscripts/main.js"></script> </body>
</html>
How can I remove that white space at the beginning of lines 2-5 without "uglyfying" the I'm writing the object inside the data
function ?如何删除第 2-5 行开头的空白而不“丑化”我在
data
function 中写入 object ?
You can remove whitespace at the beginning of the lines with a regular expression.您可以使用正则表达式删除行首的空格。
fs.writeFileSync(`${p[0]}/index.html`, data()['index.html'].replace(/^\s+/gm, '');
The m
flag makes ^
match newlines in the middle of the input string, rather than just the beginning of the string. m
标志使^
匹配输入字符串中间的换行符,而不仅仅是字符串的开头。
Another option is to use the desired indentation in the template literal.另一种选择是在模板文字中使用所需的缩进。
function data(){
return {
'index.html': `
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" media="screen" href="css/main.css" />
...
</head>
<body> <script src="myscripts/main.js"></script> </body>
</html>`,
}
}
This doesn't seem like "unglifying" it.这看起来不像是“取消”它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.