我正在尝试编写一个 webpack 插件(我的第一个!所以请多多包涵)下载 fontello 图标字体,将它们放在 dist 文件夹中,然后生成一个包含每个图标的 SASS 变量的 icons.scss 文件。
我想这有点不合常规,因为 icons.scss 文件不应该放在 dist/ 文件夹中,而是放在 src/ 文件夹中。不过,将文件放在 src/ 中似乎并非不可能,而且它需要在那里才能让我的 app.scss 导入它。
我遇到的问题是我生成的icons.scss 文件(包含在我的SASS 主入口点(app.scss)中)在编译SASS 之前没有时间生成。
有没有办法告诉 webpack 等到我的插件完成后再继续构建?
需要明确的是,我的一切工作都比较顺利,下载了字体,生成了 icons.scss 等,唯一的问题是 SASS 在 icons.scss 存在之前编译。我也不知道哪个编译器/编译钩子最适合使用,所以我也会喜欢一些输入。
请参阅相关部分的代码摘录。我留下了我觉得事情也可以改进的评论:
// Fontello API endpoint
let url = 'http://fontello.com';
// Read our fontello config JSON
let fontelloConfig = fs.createReadStream('icons.json', 'utf8');
// Send fontello config to API
request.post({url: url, formData: {config: fontelloConfig}}, (err, res, body) => {
if (err) {
return console.error(err);
}
// Fetch ZIP using the session we got back from the previous call
request.get(`http://fontello.com/${body}/get`)
// Unzip it
.pipe(unzipper.Parse())
// For each file
.on('entry', (entry) => {
// Get basename and extension
const basename = path.basename(entry.path);
const ext = path.extname(basename);
// Copy the fontello.css to the sass path
// NOTE: All of this is a mess, I'm writing the fontello.css file to src/icons.scss, then reading src/icons.scss
// only so that I can make my changes to its contents, finally I write the changed contents back to src/icons.scss
// please help me improve this part, I'm a node and webpack noob
if (basename === 'fontello.css') {
// Write fontello.css to icons.scss
entry.pipe(fs.createWriteStream('src/icons.scss')).on('finish', () => {
// Read the file...
fs.readFile('src/icons.scss', 'utf8', (err, data) => {
// NOTE: Not until this file is created should webpack continue with compilation,
// if this file doesn't exist when SASS is compiled it will fail because my app.scss is trying to import this file
fs.writeFile('src/icons.scss', makeMyChangesToTheFontelloCssFileContent(data), 'utf8', (err) => {});
});
});
}
// Copy fonts and config.json to dist
// NOTE: I'm a noob so I didn't know you're supposed to use compilation.assets[filename] = filecontent;
// I'm working on it, but please let me know if it's an easy change?
else if (entry.type === 'File' && (basename === 'config.json' || entry.path.indexOf('/font/') !== -1)) {
entry.pipe(fs.createWriteStream('dist/' + basename));
}
// Otherwise clean up(?): https://github.com/ZJONSSON/node-unzipper#parse-zip-file-contents
else {
entry.autodrain();
}
});
});
编辑:我研究了文档,但发现没有示例很难知道该怎么做。我已经在几乎每个编译器和编译钩子上设置了回调,以了解它们何时以及如何运行,但这并没有真正帮助我很多。