html-express-js 1.0.1 → 1.1.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.
package/.prettierrc.cjs CHANGED
File without changes
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Mark Kennedy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -18,7 +18,7 @@ The following shows at a high level how the package can be used as an Express te
18
18
  Set up your Express app to use this engine:
19
19
 
20
20
  ```js
21
- import htmlExpress from 'html-express-js';
21
+ import htmlExpress, { staticIndexHandler } from 'html-express-js';
22
22
 
23
23
  const app = express();
24
24
  const __dirname = resolve();
@@ -43,6 +43,16 @@ app.get('/', function (req, res, next) {
43
43
  name: 'Bob',
44
44
  });
45
45
  });
46
+
47
+ // OPTIONALLY: route all GET requests to directories
48
+ // to their associated static index.js views in the public directory
49
+ // and, if not found, route to the 404/index.js view
50
+ app.use(
51
+ staticIndexHandler({
52
+ viewsDir: `${__dirname}/public`, // root views directory to serve all index.js files
53
+ notFoundView: '404/index', // relative to viewsDir above
54
+ })
55
+ );
46
56
  ```
47
57
 
48
58
  Then you can create the associated files:
package/example/app.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import express from 'express';
2
2
  import { resolve } from 'path';
3
- import htmlExpress from '../src/index.js';
3
+ import htmlExpress, { staticIndexHandler } from '../src/index.js';
4
4
 
5
5
  const __dirname = resolve();
6
6
 
@@ -10,16 +10,14 @@ app.engine(
10
10
  'js',
11
11
  htmlExpress({
12
12
  includesDir: 'includes',
13
- notFoundView: '404/index',
14
13
  })
15
14
  );
16
15
 
17
16
  app.set('view engine', 'js');
18
17
  app.set('views', `${__dirname}/example/public`);
19
18
 
20
- app.get('/', async function (req, res) {
21
- res.render('dashboard');
22
- });
19
+ // serve all other static files like CSS, images, etc
20
+ app.use(express.static(`${__dirname}/example/public`));
23
21
 
24
22
  app.get('/hello', async function (req, res) {
25
23
  res.render('hello', {
@@ -27,7 +25,12 @@ app.get('/hello', async function (req, res) {
27
25
  });
28
26
  });
29
27
 
30
- // serve all other static files like CSS, images, etc
31
- app.use(express.static(`${__dirname}/example/public`));
28
+ // Automatically serve any index.js file as HTML in the public directory
29
+ app.use(
30
+ staticIndexHandler({
31
+ viewsDir: `${__dirname}/example/public`,
32
+ notFoundView: 'not-found', // OPTIONAL: defaults to `404/index`
33
+ })
34
+ );
32
35
 
33
36
  export default app;
@@ -1,4 +1,4 @@
1
- import { html } from '../../src/index.js';
1
+ import { html } from '../../../src/index.js';
2
2
 
3
3
  export const view = (data, state) => html`
4
4
  <!DOCTYPE html>
@@ -9,4 +9,7 @@ export const view = (/*data, state*/) => html`
9
9
  />
10
10
 
11
11
  <link rel="stylesheet" href="/main.css" />
12
+
13
+ <!-- For HMR! -->
14
+ <script src="/reload/reload.js"></script>
12
15
  `;
@@ -11,6 +11,10 @@ export const view = (data, state) => html`
11
11
  <body>
12
12
  <h1>This is the dashboard!</h1>
13
13
 
14
+ <p>
15
+ This file is served by the <code>staticIndexHandler</code> in app.js
16
+ </p>
17
+
14
18
  <p>Click <a href="/hello">here</a> to go hello route.</p>
15
19
  </body>
16
20
  </html>
File without changes
File without changes
package/example/server.js CHANGED
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "html-express-js",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "An Express template engine to render HTML views using native JavaScript",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -32,7 +32,7 @@
32
32
  "devDependencies": {
33
33
  "chokidar": "^3.5.3",
34
34
  "express": "^4.18.1",
35
- "prettier": "^2.7.0",
35
+ "prettier": "^2.7.1",
36
36
  "release-it": "^15.0.0",
37
37
  "reload": "^3.2.0"
38
38
  }
package/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
- import { basename } from 'path';
1
+ import { basename, extname } from 'path';
2
2
  import { promisify } from 'util';
3
3
  import g from 'glob';
4
+ import { stat } from 'fs/promises';
4
5
 
5
6
  const glob = promisify(g);
6
7
 
@@ -28,14 +29,14 @@ async function renderHtmlFileTemplate(path, data, state) {
28
29
  *
29
30
  * @param {string} filePath - The path to html file
30
31
  * @param {object} data - Data to be made available in view
31
- * @param {object} options - Options passed to express
32
+ * @param {object} instanceOptions - Options passed to original instantiation
32
33
  * @returns {string} HTML with includes available (appended to state)
33
34
  */
34
- async function renderHtmlFile(filePath, data = {}, options = {}) {
35
+ async function renderHtmlFile(filePath, data = {}, instanceOptions = {}) {
35
36
  const state = {
36
37
  includes: {},
37
38
  };
38
- const { includesDir } = options;
39
+ const { includesDir } = instanceOptions;
39
40
 
40
41
  const includeFilePaths = await glob(`${includesDir}/*.js`);
41
42
  for await (const includePath of includeFilePaths) {
@@ -65,15 +66,48 @@ export function html(strings, ...data) {
65
66
  return html;
66
67
  }
67
68
 
69
+ /**
70
+ * Attempts to render index.js pages when requesting to
71
+ * directories and fallback to 404/index.js if doesnt exist.
72
+ *
73
+ * @param {object} [options]
74
+ * @param {object} options.viewsDir - The directory that houses any potential index files
75
+ * @param {string} [options.notFoundView] - The path of a file relative to the views
76
+ * directory that should be served as 404 when no matching index page exists. Defaults to `404/index`.
77
+ * @returns {function} - Middleware function
78
+ */
79
+ export function staticIndexHandler(options = {}) {
80
+ const notFoundView = options.notFoundView || `404/index`;
81
+
82
+ return async function (req, res, next) {
83
+ const { path: rawPath } = req;
84
+ const fileExtension = extname(rawPath);
85
+ if (fileExtension) {
86
+ return next();
87
+ }
88
+ const sanitizedPath = rawPath.replace('/', ''); // remove beginning slash
89
+ const path = sanitizedPath ? `${sanitizedPath}/index` : 'index';
90
+ try {
91
+ await stat(`${options.viewsDir}/${path}.js`); // check if file exists
92
+ res.render(path);
93
+ } catch (e) {
94
+ if (e.code !== 'ENOENT') {
95
+ throw e;
96
+ }
97
+ res.status(404);
98
+ res.render(notFoundView);
99
+ }
100
+ };
101
+ }
102
+
68
103
  /**
69
104
  * Returns a template engine view function.
70
105
  *
71
- * @param {object} opts
106
+ * @param {object} [opts]
72
107
  * @param {object} [opts.includesDir]
73
- * @param {object} [opts.notFoundView]
74
108
  * @returns {Function}
75
109
  */
76
- export default function (opts) {
110
+ export default function (opts = {}) {
77
111
  return async (filePath, data, callback) => {
78
112
  const viewsDir = data.settings.views;
79
113
  const includePath = opts.includesDir || 'includes';
@@ -81,9 +115,6 @@ export default function (opts) {
81
115
  const sanitizedOptions = {
82
116
  viewsDir,
83
117
  includesDir: `${viewsDir}/${includePath}`,
84
- notFoundView: opts.notFoundView
85
- ? `${viewsDir}/${opts.notFoundView}.js`
86
- : `${viewsDir}/404/index.js`,
87
118
  };
88
119
 
89
120
  const html = await renderHtmlFile(filePath, data, sanitizedOptions);