> For the complete documentation index, see [llms.txt](https://overleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://overleaf-pro.ayaka.space/latex/zh-tw/wen-jian-jie-gou/08-multi-file-latex-projects.md).

# 多檔案 LaTeX 專案

## 簡介

在 [大型 LaTeX 文件](/latex/zh-tw/wen-jian-jie-gou/07-management-in-a-large-project.md) 通常會有數個 `.tex` 檔案，通常每個章節或節各有一個，然後再將它們合併起來產生單一輸出。這有助於保持一切有條不紊，也讓文件更容易除錯，但隨著文件變大，編譯所需時間也會變長。這會讓人感到沮喪，因為通常每次只會想針對某個特定檔案進行編輯。

克服這個問題的自然做法是分別編譯每個檔案。多檔專案中有兩個主要套件可讓你編譯單一檔案。你的選擇取決於你的需求。

* 使用 [該 **subfiles** 套件](#the-subfiles-package) 你可以獨立編譯每個子檔案，而且每個子檔案都會自動使用主檔案中的前言區。
* 使用 [該 **standalone** 套件](#the-standalone-package) 由於每個子檔案都可作為獨立檔案運作，之後可將子檔案合併到主文件中，並從每個檔案擷取其前言區。尤其適合你需要在多份文件中重複使用同一個檔案時，TikZ 圖形就是這個情況的好例子。

## Overleaf .tex 檔案中 \documentclass 的備註

如以下影片片段所示，即使你已設定專案的主 `.tex` 檔案，你仍可選擇另一個檔案來編譯——前提是它包含一個 `\documentclass` 宣告。然而，為了確保專案中的所有元素都能正確編譯——例如詞彙表、存取通往 `.bib` 檔案等的路徑——我們強烈建議你只編譯專案根目錄中的檔案。

{% embed url="<https://videos.ctfassets.net/nrgyaltdicpt/U2nGfRx9NwNGX0vWXNebP/1ca4b9a4b2f36d5ca9c0dbaa87f44bfa/maincompile.mp4>" %}

## subfiles 套件

這個套件適用於大多數情況，而且真的很容易使用。

本節中的範例具有下列階層式檔案結構：

![CompileSubfilesEx1OverleafV2.png](/files/478c69d17b772314a8a1032f286c87aada62a594)

### 主檔案

在主檔案中需要兩個特殊指令。

```latex
\documentclass{article}
\usepackage{graphicx}
\graphicspath{{images/}}

\usepackage{blindtext}

\usepackage{subfiles} % 最好在前言區最後載入

\title{subfiles 套件範例}
\author{Overleaf}
\date{ }

\begin{document}

\maketitle

\section{簡介}

\subfile{sections/introduction}

\section{第二節}

\subfile{sections/section2}

\end{document}
```

![CompileSubfilesEx1aOverleafV2.png](/files/ef9ba84ab0a2dda91d4ee775b6fc9cb3df42c19a)

逐檔編譯需要這一行

```latex
\usepackage{subfiles}
```

放在前言區中，這會啟用 `subfiles` 套件。接著，每個外部子檔案都必須使用命令 `\subfile{}`。在這個範例中，檔案 `introduction.tex` 和 `section2.tex` 會從下列位置匯入主檔案： `sections` 資料夾。請注意，檔案副檔名不是必要的。

[開啟一個 `subfiles` 套件範例](https://www.overleaf.com/project/new/template/19626?id=66392908\&templateName=Subfiles+package+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

### 子檔案

一旦你設定好主檔案，每個子檔案都必須具有特殊的結構。

```latex
\documentclass[../main.tex]{subfiles}
\graphicspath{{\subfix{../images/}}}
\begin{document}
\textbf{你好，世界！}
\begin{figure}[bh]
\centering
\includegraphics[width=3cm]{overleaf-logo}

\label{fig:img1}
\caption{Overleaf 標誌}
\end{figure}

你好，這裡有一些沒有意義的文字……

\end{document}
```

![CompileSubfilesEx2OverleafV2.png](/files/af2a636ee88dd59d6d1bc3a5f55e5ae7ed7c14a7)

現在這個檔案可以作為獨立檔案編譯，文件類別與其餘前言區將與主文件中定義的相同。

這裡的第一個指令是

```latex
\documentclass[../main.tex]{subfiles}
```

方括號中的參數 `../main.tex`，它是到主文件的相對路徑。在此情況下，檔案 `introduction.tex` 位於資料夾 `sections`中，因此檔案 `main.tex` 位於目前資料夾的上一層（這就是 `../` 的意思）。

你也需要使用 `\subfix` 命令，並在指定 `\graphicspath` 中插入一個 `introduction.tex`:

```latex
\graphicspath{{\subfix{../images/}}}
```

之後，實際內容是輸入在 `\begin{document}` 和 `\end{document}`。此環境外的所有內容都會被忽略，或者更精確地說，會被視為前言區的一部分。避免在檔案的頂端與底端留下空白行。

[開啟一個 `subfiles` 套件範例](https://www.overleaf.com/project/new/template/19626?id=66392908\&templateName=Subfiles+package+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## standalone 套件

此套件 **standalone** 提供與 **subfiles** 相同的功能，且更具彈性，但語法更複雜，也更容易出錯。主要差異在於每個子檔案都有自己的前言區。

本節中的範例具有下列階層式檔案結構：

![CompileSubfilesEx3OverleafV2.png](/files/3d3b25736a11441a68984d4392bba1d478684050)

### 主檔案

主檔案與任何其他多檔案專案的主檔案非常相似。

```latex
\documentclass{article}
\usepackage[subpreambles=true]{standalone}
\usepackage{import}

\title{standalone 套件範例}
\author{Overleaf}
\date{2021 年 5 月}

\begin{document}

\maketitle

\section{第一節}
\import{sections/}{introduction}

\section{第二節}
\import{sections/}{section2}

\end{document}
```

![CompileSubfilesEx3Overleaf.png](/files/f6822f589be5643fb6d3c075442382733b3b7af7)

這一行

```latex
\usepackage[subpreambles=true]{standalone}
```

啟用 **standalone** 套件，它應放在文件前面較早的位置。方括號中的參數會告訴 LaTeX 從每個子檔案匯入前言區（套件只會被匯入一次）；若省略，請確保你已在主文件的前言區中放入所有必要的指令，讓子檔案能正常運作。必須小心，因為不同前言區之間可能存在不相容。

在主文件的正文中，每個子檔案都使用 `\import{}{}`標準的 `\input{}` 指令也可以使用，但此範例中建議使用 [以管理大型專案](/latex/zh-tw/wen-jian-jie-gou/07-management-in-a-large-project.md) ，因為它能防止巢狀檔案中的錯誤。

[在 Overleaf 中開啟一個 `standalone` 套件範例](https://www.overleaf.com/project/new/template/19636?id=66440758\&templateName=Standalone+package+example\&latexEngine=pdflatex\&texImage=\&mainFile=)

### 子檔案

每個子檔案都必須有自己的前言區，並匯入作為獨立文件運作所需的所有套件。

```latex
\documentclass[class=article, crop=false]{standalone}
\usepackage[subpreambles=true]{standalone}
\usepackage{import}
\usepackage{blindtext}

\begin{document}
這條線下方將會呈現一個 TikZ 圖形

\begin{figure}[ht]
\centering
\subimport{../}{diagram.tex}
\label{fig:tikzexample}
\caption{一個漂亮簡單的圖示}
\end{figure}

\blindtext
\end{document}
```

![CompileSubfilesEx4OverleafV2.png](/files/7570a87744bdaa381f6ccb18b0a395c5f497fa51)

子檔案中的第一行是

```latex
\documentclass[class=article, crop=false]{standalone}
```

這表示這是一個要與此套件一起使用的檔案， **standalone** 套件，方括號中有兩個可選參數。

* `class=article`。設定 `article` 作為底層類別，也可以使用任何其他類別：book、report 等等。（beamer 除外。）
* `crop=false`。如果省略此選項，輸出將裁切到最小尺寸。

下一個指令不是必須的

```latex
\usepackage[subpreambles=true]{standalone}
```

但在此範例中必須使用，因為這裡有一個巢狀的 **standalone** 檔案在這裡。一個 [tikz 圖形](/latex/zh-tw/tu-biao-yu-biao-ge/05-tikz-package.md) 是透過 [`\subimport{../}{diagram.tex}`](/latex/zh-tw/wen-jian-jie-gou/07-management-in-a-large-project.md#importing-files)，你可以在下方看到 "diagram.tex" 檔案的內容：

```latex
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}

\begin{tikzpicture}[
roundnode/.style={circle, draw=green!60, fill=green!5, very thick, minimum size=7mm},
squarednode/.style={rectangle, draw=red!60, fill=red!5, very thick, minimum size=5mm},
]
%節點
\node[squarednode]      (maintopic)                              {2};
\node[roundnode]        (uppercircle)       [above=of maintopic] {1};
\node[squarednode]      (rightsquare)       [right=of maintopic] {3};
\node[roundnode]        (lowercircle)       [below=of maintopic] {4};

%線條
\draw[->] (uppercircle.south) -- (maintopic.north);
\draw[->] (maintopic.east) -- (rightsquare.west);
\draw[->] (rightsquare.south) .. controls +(down:7mm) and +(right:7mm) .. (lowercircle.east);

\end{tikzpicture}
\end{document}
```

[在 Overleaf 中開啟這個 Standalone TikZ 範例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Standalone+TikZ+example\&snip=%5Cdocumentclass%7Bstandalone%7D%0A%5Cusepackage%7Btikz%7D%0A%5Cusetikzlibrary%7Bpositioning%7D%0A%5Cbegin%7Bdocument%7D%0A%0A%5Cbegin%7Btikzpicture%7D%5B%0Aroundnode%2F.style%3D%7Bcircle%2C+draw%3Dgreen%2160%2C+fill%3Dgreen%215%2C+very+thick%2C+minimum+size%3D7mm%7D%2C%0Asquarednode%2F.style%3D%7Brectangle%2C+draw%3Dred%2160%2C+fill%3Dred%215%2C+very+thick%2C+minimum+size%3D5mm%7D%2C%0A%5D%0A%25Nodes%0A%5Cnode%5Bsquarednode%5D++++++%28maintopic%29++++++++++++++++++++++++++++++%7B2%7D%3B%0A%5Cnode%5Broundnode%5D++++++++%28uppercircle%29+++++++%5Babove%3Dof+maintopic%5D+%7B1%7D%3B%0A%5Cnode%5Bsquarednode%5D++++++%28rightsquare%29+++++++%5Bright%3Dof+maintopic%5D+%7B3%7D%3B%0A%5Cnode%5Broundnode%5D++++++++%28lowercircle%29+++++++%5Bbelow%3Dof+maintopic%5D+%7B4%7D%3B%0A%0A%25Lines%0A%5Cdraw%5B-%3E%5D+%28uppercircle.south%29+--+%28maintopic.north%29%3B%0A%5Cdraw%5B-%3E%5D+%28maintopic.east%29+--+%28rightsquare.west%29%3B%0A%5Cdraw%5B-%3E%5D+%28rightsquare.south%29+..+controls+%2B%28down%3A7mm%29+and+%2B%28right%3A7mm%29+..+%28lowercircle.east%29%3B%0A%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

![CompileSubfilesEx5.png](/files/7d29b786dcfcad383232d643e640dd81e97e2c03)

這是此套件的主要特色 **standalone**，你可以將這個檔案匯入任何其他文件並重複使用這段程式碼。舉例來說，這張圖之後可在簡報中直接使用，無須再修改。

[在 Overleaf 中開啟一個 `standalone` 套件範例](https://www.overleaf.com/project/new/template/19636?id=66440758\&templateName=Standalone+package+example\&latexEngine=pdflatex\&texImage=\&mainFile=)

## 延伸閱讀

更多資訊請參見

* [大型專案中的管理](/latex/zh-tw/wen-jian-jie-gou/07-management-in-a-large-project.md)
* [章節與方程式交叉參照](/latex/zh-tw/wen-jian-jie-gou/03-cross-referencing-sections-equations-and-floats.md)
* [索引](/latex/zh-tw/wen-jian-jie-gou/04-indices.md)
* [詞彙表](/latex/zh-tw/wen-jian-jie-gou/05-glossaries.md)
* [超連結](/latex/zh-tw/wen-jian-jie-gou/09-hyperlinks.md)
* [頁碼編號](/latex/zh-tw/ge-shi-hua/03-page-numbering.md)
* [單面與雙面文件](/latex/zh-tw/ge-shi-hua/08-single-sided-and-double-sided-documents.md)
* [多欄排版](/latex/zh-tw/ge-shi-hua/09-multiple-columns.md)
* [段落格式設定](/latex/zh-tw/ge-shi-hua/04-articles-how-to-change-paragraph-spacing-in-latex.md)
* [頁面大小與邊界](/latex/zh-tw/ge-shi-hua/07-page-size-and-margins.md)
* [計數器](/latex/zh-tw/ge-shi-hua/10-counters.md)
* [邊界註記](/latex/zh-tw/ge-shi-hua/15-margin-notes.md)
* [粗體、斜體與底線](/latex/zh-tw/latex-ji-chu/03-bold-italics-and-underlining.md)
* [字型大小、字族與樣式](/latex/zh-tw/zi-xing/01-font-sizes-families-and-styles.md)
* [字型字體](/latex/zh-tw/zi-xing/02-font-typefaces.md)
* [使用 XeLaTeX 支援現代字型](/latex/zh-tw/zi-xing/03-xelatex.md)
* [國際語言支援](/latex/zh-tw/yu-yan/03-international-language-support.md)
* [字型大小、字族與樣式](/latex/zh-tw/zi-xing/01-font-sizes-families-and-styles.md)
* [編譯大型專案](/latex/zh-tw/zhi-shi-ku/038-fixing-and-preventing-compile-timeouts.md#compiling-big-projects)
* [插入圖片](/latex/zh-tw/geng-duo-zhu-ti/27-inserting-images.md)
* [TikZ 套件](/latex/zh-tw/tu-biao-yu-biao-ge/05-tikz-package.md)
* [撰寫你自己的套件](/latex/zh-tw/lei-bie-dang/03-writing-your-own-package.md)
* [撰寫你自己的類別](/latex/zh-tw/lei-bie-dang/04-writing-your-own-class.md)
* [該 **subfiles** 套件說明文件](http://repositorios.cpai.unb.br/ctan/macros/latex/contrib/subfiles/subfiles.pdf)
* [該 **standalone** 套件說明文件](http://repositorios.cpai.unb.br/ctan/macros/latex/contrib/standalone/standalone.pdf)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://overleaf-pro.ayaka.space/latex/zh-tw/wen-jian-jie-gou/08-multi-file-latex-projects.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
