导入文件
2026/7/22大约 2 分钟
导入文件
支持导入的文件类型:
svg、txt、md。。。
使用情景:展示配置文件代码
当前展示方法:拷贝配置文件内容到md的代码块中
问题:配置常常发生变化,每次更改配置文件都要重新拷贝,容易出现遗漏、拷贝错误的情况
改进:使用导入文件功能,呈现的内容和文件内容同步,不需要手动拷贝
配置导入的文件路径
使用@src 作为起始路径(源文件夹-存放导入文件的文件夹 的别名)
//...
import { getDirname, path } from "vuepress/utils";
const __dirname = getDirname(import.meta.url);
export default defineUserConfig({
base: "/",
theme: hopeTheme({
markdown: {
// 添加 `@src` 别名支持
include: {
resolvePath: (file) => {
if (file.startsWith("@src"))
return file.replace("@src", path.resolve(__dirname, "public"));
return file;
},
},
},
}),
});| 行号 | 功能 | 说明 |
|---|---|---|
| 2 | 引入行数及变量 | |
| 4 | 当前配置文件路径 | |
| 12 | 启用include | |
| 14,15 | 对于以@src开头的路径将其切换为指定的源文件夹路径 |
官方文档中是对 config.ts 进行配置
import { hopeTheme } from "vuepress-theme-hope";
import theme from "./theme.js";- hopeTheme: 是函数名称,导入时带{}
- theme:是对象名称,带入时不带{}
不是很理解:
export default hopeTheme();在ts中创建了hopeTheme()函数返回的对象并导出
config.ts 中import时如何确定 theme 就是 前面export的?是不是因为export的只有一个,所以不用对应名称?
照理来说config.ts中的theme 是 前面hopeTheme的别名,完整的语法应该类似于
import hopeTheme from "" as themeSyntax
File not found
指定文件内容的范围 - 行
<!-- @include: filename{start-end} --><!-- @include: filename{start-} --<!-- @include: filename{-end} -->
示例;
3-7
File not found
3-
File not found
-7
File not found
file region
通过一个“界碑”指定要显示的文件内容范围
<!-- @include: filename#region -->
- 在文件中指定file region
<!-- #region snippet -->
File region is a concept in vscode, where the region content is surrounded by region and endregion
<!-- #endregion snippet -->这里region的名称是 snippet
不同文件因为注释格式不同,所以file region的指定格式也有所区别:
C/C++
#pragma region snippet
int f() {
for (int item : v) std::cout << item << std::endl;
return v.size();
}
#pragma endregion snippetts/js
// #region snippet
const mdIt = new MarkdownIt().use(include, {
// your options, currentPath is required
currentPath: (env) => env.filePath,
});
// #endregion snippet- 导入文件,指定file region名称
File not found其它
- 无法使用preview 预览导入文件的代码
- 代码块中的导入文件代码仍然被解析