英文:
How to copy and apply a patch/diff to a svelte file on build?
问题
我正在使用SvelteKit构建一个Svelte的npm模块。它提供了几乎相同的组件,只有一些行不同。我想根据原始组件生成一个新组件。在构建过程中,我如何复制一个文件并应用补丁/差异呢?我应该研究Svelte预处理器、Vite预处理器和构建,还是其他方法?
英文:
I'm building a svelte npm module with sveltekit. It supplies components that are identical except for a couple lines. I'd like to generate one of the components based on the original. How can I copy a file and apply a patch/diff to it on build? Should I look into the svelte preprocessor, vite preprocessor and build, or something else?
答案1
得分: 1
以下是翻译好的部分:
这实际上非常容易做
以此作为例子:
import { readFileSync } from 'fs';
import { resolve } from 'path';
export default function () {
return {
name: 'my-plugin',
load(file) {
if (file === resolve(<目标文件路径>)) {
let code = readFileSync(<原始文件路径>, 'utf-8');
// 对 `code` 应用所需的任何修补
return { code, map: null };
}
}
};
}
如果这个文件是 myPlugin.js
,那么你只需要将它添加到你的 vite.config.ts
中,像这样:
import MyPlugin from 'myPlugin.js';
const config: UserConfig = {
plugins: [
MyPlugin()
]
};
export default config;
我有几个这样构建的插件,它们工作得非常好。通过查看 Vite 的文档,甚至可以实现一些高级功能,比如为客户端返回一些内容,为服务器返回另一些内容等。
不过,我要提醒你一下:尽管这样做看起来很酷,但我发现在代码中应用解决方案要比编译后的解决方案好得多,因为编译后的解决方案不仅感觉像魔法,而且它们与真实源代码偏离,所以调试可能会变得更加困难(在这种情况下,vite-plugin-inspect
对我来说非常有价值)。
对于你的情况,也许可以尝试抽象或设计模式,比如装饰器。不过,我不了解你的具体用例,所以建议你要慎重考虑我的建议。
话虽如此,玩得开心!
英文:
It is actually very easy to do
Take this as an example:
import { readFileSync } from 'fs';
import { resolve } from 'path';
export default function () {
return {
name: 'my-plugin',
load(file) {
if (file === resolve(<target file path>)) {
let code = readFileSync(<original file path>, 'utf-8');
// Apply any patch required to `code`
return { code, map: null };
}
}
};
}
If this file was myPlugin.js
then you just need to add it into your vite.config.ts
like this:
import MyPlugin from 'myPlugin.js';
const config: UserConfig = {
plugins: [
MyPlugin()
]
};
export default config;
I have several of those plugins build like this and they work like a charm. By inspecting Vite's documentation, you can even do fancy stuff like returning some contents for the client and some other for the server etc.
However, let me make you a warning: as cool as doing this might seem, I've found that applying in-code solutions are far better than compiled ones since the compiled solutions not only feel like magic but they also diverge from the real source code so debugging it can become tricker (under those circumstances, the vite-plugin-inspect
has proven very valuable to me).
In your case, I would, perhaps experiment with abstraction or design patterns like the decorator. However, I'm unaware of your specific use case so take my advice with a pinch of salt.
That said, have fun!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论