"scripts": {
"build-css": "sass theme/app.scss C:\Users\ragha\AppData\Roaming\style.css"
}
这只适用于 Windows 并且路径是硬编码的。我不想对路径进行硬编码,而是想从我的
script.js
文件中获取 css 文件的路径,它会根据某些条件记录 css 路径。
您可以使用
saas
包以编程方式编译您的 SASS 文件。
首先,确保您的项目中安装了 sass 包:
$ npm install sass
然后,将您的编译说明放在文件中:
// build-css.js
const sass = require('sass');
const fs = require('fs');
const path = require('path');
// This will consume your `script.js` file:
const script = require('./path/to/your/script.js');
const cssPath = script.getCssPath();
// Assuming getCssPath is a function that returns the path
// to the css file, make sure to export the getCssPath function
// from your script.js file so that you can use it from here.
// ...or simply insert your path resolving logic here, instead.
const inputPath = path.join(__dirname, 'theme/app.scss');
const outputPath = path.join(cssPath, 'style.css');
sass.render({ file: inputPath }, (error, result) => {
if (error) {
console.error(`Error rendering SASS: ${error.message}`);
return;
}
fs.writeFile(outputPath, result.css, (err) => {
if (err) {
console.error(`Error writing CSS file: ${err.message}`);
return;
}
console.log(`CSS successfully written to: ${outputPath}`);
});
});
更新您的
package.json
文件以使用新脚本:
"scripts": {
"build-css": "node build-css.js"
}
现在,当您运行
build-css
脚本时,它将以编程方式使用 sass
包来编译您的 SASS 文件并将输出写入动态 CSS 路径:
$ npm run build-css
更新: 您可以使用命令替换将 stdout 分配给命令行中的变量。语法因操作系统而异。
如果你的script.js直接将输出路径写到stdout,例如:
// script.js dumb example
process.stdout.write('C:\\Users\\ragha\\AppData\\Roaming\\style.css')
您可以使用命令替换将 stdout 分配给命令行中的变量。语法因操作系统而异:
基于 Unix 的系统(Linux 和 macOS):
"scripts": {
"build-css": "sass theme/app.scss $(node script.js)"
}
对于 Windows,您可以通过 for 命令使用类似的方法:
"scripts": {
"build-css": "for /F %i in ('node script.js') do sass theme/app.scss %i"
}
请记住,Windows 版本可能无法在所有环境中运行,并且可能存在包含空格的路径问题。对于更可靠和跨平台的解决方案,我建议使用上面的 build-css.js 方法。