vite-file-include 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +206 -0
  2. package/package.json +25 -0
  3. package/src/index.js +227 -0
package/README.md ADDED
@@ -0,0 +1,206 @@
1
+ # vite-plugin-file-include
2
+
3
+ `vite-plugin-file-include` is an advanced Vite plugin designed to facilitate the inclusion of external HTML files, looping through data, and conditional rendering within your HTML files. It is particularly useful for managing repetitive HTML structures in static sites or templating environments.
4
+
5
+ ## Features
6
+
7
+ - File inclusion with support for nested includes
8
+ - Looping through data arrays or JSON files
9
+ - Conditional rendering
10
+ - Caching mechanism for improved performance
11
+ - Custom function support for advanced templating
12
+ - Asynchronous file processing
13
+ - Enhanced error handling and debugging
14
+
15
+ ## Installation
16
+
17
+ Install the plugin via npm:
18
+
19
+ ```bash
20
+ npm install vite-plugin-file-include
21
+ ```
22
+
23
+ ## Configuration
24
+
25
+ To use the plugin, import and configure it in your `vite.config.js`:
26
+
27
+ ```javascript
28
+ import fileIncludePlugin from 'vite-plugin-file-include';
29
+
30
+ export default {
31
+ plugins: [
32
+ fileIncludePlugin({
33
+ includePattern: "@@include",
34
+ loopPattern: "@@loop",
35
+ ifPattern: "@@if",
36
+ baseDir: process.cwd(),
37
+ context: {},
38
+ customFunctions: {},
39
+ cacheTimeout: 5000
40
+ }),
41
+ ],
42
+ };
43
+ ```
44
+
45
+ ### Plugin Options
46
+
47
+ - `includePattern` (default: `@@include`): The pattern used to include external HTML files.
48
+ - `loopPattern` (default: `@@loop`): The pattern used to loop through data arrays.
49
+ - `ifPattern` (default: `@@if`): The pattern used to conditionally render content.
50
+ - `baseDir` (default: `process.cwd()`): The base directory for resolving paths.
51
+ - `context` (default: `{}`): An object containing global variables that can be used in includes, loops, and conditionals.
52
+ - `customFunctions` (default: `{}`): An object containing custom functions that can be used in expressions.
53
+ - `cacheTimeout` (default: `5000`): The time (in milliseconds) after which cached content is invalidated.
54
+
55
+ ## Directives
56
+
57
+ ### `@@include`
58
+
59
+ The `@@include` directive allows you to include the content of another HTML file within your main file.
60
+
61
+ **Syntax:**
62
+
63
+ ```html
64
+ @@include('path/to/file.html');
65
+ ```
66
+
67
+ **With Data:**
68
+
69
+ ```html
70
+ @@include('path/to/file.html', { "key": "value" });
71
+ ```
72
+
73
+ **Example** (`file.html`):
74
+
75
+ ```html
76
+ <div>{{ key }}</div>
77
+ ```
78
+
79
+ ### `@@loop`
80
+
81
+ The `@@loop` directive enables you to repeat a block of HTML for each item in a data array or JSON file.
82
+
83
+ **Syntax:**
84
+
85
+ ```html
86
+ @@loop('path/to/template.html', 'data.json');
87
+ ```
88
+
89
+ **With Inline Data:**
90
+
91
+ ```html
92
+ @@loop('path/to/template.html', [{ "key": "value" }, { "key": "another value" }]);
93
+ ```
94
+
95
+ **Example Template** (`template.html`):
96
+
97
+ ```html
98
+ <article>
99
+ <h2>{{ key }}</h2>
100
+ </article>
101
+ ```
102
+
103
+ ### `@@if`
104
+
105
+ The `@@if` directive allows conditional rendering based on an expression.
106
+
107
+ **Syntax:**
108
+
109
+ ```html
110
+ @@if(condition) {
111
+ <!-- HTML content -->
112
+ }
113
+ ```
114
+
115
+ **Example:**
116
+
117
+ ```html
118
+ @@if(name === 'John') {
119
+ <p>Welcome, John!</p>
120
+ }
121
+ ```
122
+
123
+ ## Custom Functions
124
+
125
+ You can define custom functions to use in your templates. These functions are passed to the plugin through the `customFunctions` option:
126
+
127
+ ```javascript
128
+ fileIncludePlugin({
129
+ customFunctions: {
130
+ uppercase: (str) => str.toUpperCase(),
131
+ currentYear: () => new Date().getFullYear()
132
+ }
133
+ })
134
+ ```
135
+
136
+ You can then use these functions in your templates:
137
+
138
+ ```html
139
+ <p>{{ uppercase(name) }}</p>
140
+ <footer>&copy; {{ currentYear() }}</footer>
141
+ ```
142
+
143
+ ## Example Usage
144
+
145
+ Below is an example of how you might structure your HTML files using the plugin's directives:
146
+
147
+ ```html
148
+ <!-- main.html -->
149
+ <html>
150
+ <body>
151
+ @@include('header.html', { "title": "My Website" });
152
+
153
+ @@loop('partials/article.html', 'data/articles.json');
154
+
155
+ @@if(showFooter) {
156
+ @@include('footer.html');
157
+ }
158
+ </body>
159
+ </html>
160
+ ```
161
+
162
+ ### Example Files
163
+
164
+ - `header.html`:
165
+
166
+ ```html
167
+ <header>
168
+ <h1>{{ uppercase(title) }}</h1>
169
+ </header>
170
+ ```
171
+
172
+ - `partials/article.html`:
173
+
174
+ ```html
175
+ <article>
176
+ <h2>{{ title }}</h2>
177
+ <p>{{ content }}</p>
178
+ </article>
179
+ ```
180
+
181
+ - `data/articles.json`:
182
+
183
+ ```json
184
+ [
185
+ {
186
+ "title": "Article 1",
187
+ "content": "Content of the first article."
188
+ },
189
+ {
190
+ "title": "Article 2",
191
+ "content": "Content of the second article."
192
+ }
193
+ ]
194
+ ```
195
+
196
+ ## Error Handling
197
+
198
+ If there is an error parsing JSON data or including a file, the plugin will log a detailed error message to the console. This helps in debugging while ensuring that your build process continues without interruption.
199
+
200
+ ## Caching
201
+
202
+ The plugin implements a caching mechanism to improve performance, especially for larger projects with many includes. Cached content is automatically invalidated after the specified `cacheTimeout`.
203
+
204
+ ## License
205
+
206
+ This project is licensed under the MIT License. See the LICENSE file for more details.
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "vite-file-include",
3
+ "version": "1.0.0",
4
+ "description": "A Vite plugin for file inclusion, loops, and conditionals in HTML files",
5
+ "main": "src/index.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "test": "echo \"Error: no test specified\" && exit 1"
9
+ },
10
+ "keywords": [
11
+ "vite",
12
+ "plugin",
13
+ "file-include",
14
+ "html"
15
+ ],
16
+ "author": "Ahmed Abdulgid",
17
+ "license": "MIT",
18
+ "peerDependencies": {
19
+ "vite": "^4.0.0"
20
+ },
21
+ "dependencies": {
22
+ "fs": "0.0.1-security",
23
+ "path": "^0.12.7"
24
+ }
25
+ }
package/src/index.js ADDED
@@ -0,0 +1,227 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+
4
+ function fileInclude(options = {}) {
5
+ const {
6
+ includePattern = "@@include",
7
+ loopPattern = "@@loop",
8
+ ifPattern = "@@if",
9
+ baseDir = process.cwd(),
10
+ context = {},
11
+ } = options;
12
+
13
+ return {
14
+ name: "vite-plugin-file-include",
15
+
16
+ transformIndexHtml(html) {
17
+ return processIncludes(
18
+ html,
19
+ baseDir,
20
+ includePattern,
21
+ loopPattern,
22
+ ifPattern,
23
+ context
24
+ );
25
+ },
26
+
27
+ transform(code, id) {
28
+ if (id.endsWith(".html")) {
29
+ return processIncludes(
30
+ code,
31
+ path.dirname(id),
32
+ includePattern,
33
+ loopPattern,
34
+ ifPattern,
35
+ context
36
+ );
37
+ }
38
+ return code;
39
+ },
40
+
41
+ handleHotUpdate({ file, server }) {
42
+ if (file.endsWith(".html")) {
43
+ server.ws.send({
44
+ type: "full-reload",
45
+ });
46
+ }
47
+ },
48
+ };
49
+ }
50
+
51
+ function processIncludes(
52
+ content,
53
+ dir,
54
+ includePattern,
55
+ loopPattern,
56
+ ifPattern,
57
+ context
58
+ ) {
59
+ content = processIncludesWithPattern(
60
+ content,
61
+ dir,
62
+ includePattern,
63
+ loopPattern,
64
+ ifPattern,
65
+ context
66
+ );
67
+ content = processLoops(content, dir, loopPattern, context);
68
+ content = processConditionals(
69
+ content,
70
+ dir,
71
+ ifPattern,
72
+ includePattern,
73
+ loopPattern,
74
+ context
75
+ );
76
+
77
+ return content;
78
+ }
79
+
80
+ function processIncludesWithPattern(
81
+ content,
82
+ dir,
83
+ includePattern,
84
+ loopPattern,
85
+ ifPattern,
86
+ context
87
+ ) {
88
+ const regex = new RegExp(
89
+ `${includePattern}\\(\\s*['"](.+?)['"]\\s*,?\\s*({[\\s\\S]*?})?\\s*\\);`,
90
+ "g"
91
+ );
92
+
93
+ return content.replace(regex, (match, filePath, jsonData) => {
94
+ const includePath = path.resolve(dir, filePath);
95
+ let data = {};
96
+
97
+ if (jsonData) {
98
+ try {
99
+ data = JSON.parse(jsonData);
100
+ } catch (error) {
101
+ console.error(`Failed to parse JSON data: ${jsonData}`);
102
+ }
103
+ }
104
+
105
+ try {
106
+ let includedContent = fs.readFileSync(includePath, "utf-8");
107
+ includedContent = injectData(includedContent, { ...context, ...data });
108
+ return processIncludes(
109
+ includedContent,
110
+ path.dirname(includePath),
111
+ includePattern,
112
+ loopPattern,
113
+ ifPattern,
114
+ context
115
+ );
116
+ } catch (error) {
117
+ console.error(`Failed to include file: ${includePath}`);
118
+ return "";
119
+ }
120
+ });
121
+ }
122
+
123
+ function processLoops(content, dir, loopPattern, context) {
124
+ const regex = new RegExp(
125
+ `${loopPattern}\\(\\s*['"](.+?)['"]\\s*,\\s*(\\[[\\s\\S]*?\\]|['"](.+?)['"])\\s*\\);`,
126
+ "g"
127
+ );
128
+
129
+ return content.replace(regex, (match, filePath, jsonArrayOrFilePath) => {
130
+ const loopPath = path.resolve(dir, filePath);
131
+ let dataArray = [];
132
+
133
+ try {
134
+ // Detect if the second argument is a JSON file path or a JSON array
135
+ if (
136
+ jsonArrayOrFilePath.startsWith("[") ||
137
+ jsonArrayOrFilePath.startsWith("{")
138
+ ) {
139
+ // Handle JSON array or object directly provided in the directive
140
+ dataArray = JSON.parse(jsonArrayOrFilePath);
141
+ } else {
142
+ // Handle JSON file path
143
+ const jsonFilePath = path.resolve(
144
+ dir,
145
+ jsonArrayOrFilePath.replace(/['"]/g, "")
146
+ );
147
+ const jsonData = fs.readFileSync(jsonFilePath, "utf-8");
148
+ dataArray = JSON.parse(jsonData);
149
+ }
150
+ } catch (error) {
151
+ console.error(`Failed to parse JSON: ${jsonArrayOrFilePath}`);
152
+ console.error(error);
153
+ }
154
+
155
+ try {
156
+ let loopTemplate = fs.readFileSync(loopPath, "utf-8");
157
+ return dataArray.map((data) => injectData(loopTemplate, data)).join("");
158
+ } catch (error) {
159
+ console.error(`Failed to include file: ${loopPath}`);
160
+ return "";
161
+ }
162
+ });
163
+ }
164
+
165
+ function processConditionals(
166
+ content,
167
+ dir,
168
+ ifPattern,
169
+ includePattern,
170
+ loopPattern,
171
+ context
172
+ ) {
173
+ const regex = new RegExp(
174
+ `${ifPattern}\\s*\\(([^)]+)\\)\\s*{([\\s\\S]*?)};\\s*`,
175
+ "g"
176
+ );
177
+
178
+ return content.replace(regex, (match, condition, body) => {
179
+ try {
180
+ const func = new Function(
181
+ "data",
182
+ "with (data) { return " + condition + "; }"
183
+ );
184
+ const result = func(context);
185
+
186
+ if (result) {
187
+ return processIncludesWithPattern(
188
+ body.trim(),
189
+ dir,
190
+ includePattern,
191
+ loopPattern,
192
+ ifPattern,
193
+ context
194
+ );
195
+ }
196
+
197
+ return "";
198
+ } catch (error) {
199
+ console.error(`Failed to evaluate condition: ${condition}`);
200
+ console.error(error);
201
+ return "";
202
+ }
203
+ });
204
+ }
205
+
206
+ function injectData(content, data) {
207
+ return content.replace(/\{\{\s*(.*?)\s*\}\}/g, (match, expression) => {
208
+ try {
209
+ const result = evalExpression(expression, data);
210
+ return result !== undefined ? result : match;
211
+ } catch (error) {
212
+ console.error(`Failed to evaluate expression: ${expression}`);
213
+ console.error(error);
214
+ return match;
215
+ }
216
+ });
217
+ }
218
+
219
+ function evalExpression(expression, data) {
220
+ const func = new Function(
221
+ "data",
222
+ "with (data) { return " + expression + "; }"
223
+ );
224
+ return func(data);
225
+ }
226
+
227
+ export default fileInclude;