tshtml-loader 1.2.1 → 1.4.3

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.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=export-template.d.ts.map
@@ -0,0 +1,78 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ /**
38
+ * CLI helper to compile a single .tshtml file to .html on disk.
39
+ */
40
+ const fs_1 = require("fs");
41
+ const path = __importStar(require("node:path"));
42
+ const index_1 = require("./index");
43
+ // ----------------------------------------------------------------------------------
44
+ if (process.argv.length !== 3) {
45
+ console.error("Please specify one .tshtml file");
46
+ process.exit();
47
+ }
48
+ const fileName = process.argv[2];
49
+ const extension = path.extname(fileName).toLowerCase();
50
+ if (extension !== ".tshtml") {
51
+ console.error("Input file must have .tshtml extension");
52
+ process.exit();
53
+ }
54
+ const fileNameNoExtension = fileName.substr(0, fileName.length - extension.length);
55
+ const outputFileName = fileNameNoExtension + ".html";
56
+ (0, fs_1.readFile)(fileName, { encoding: 'utf-8' }, function (err, data) {
57
+ if (!err) {
58
+ // Transform the source
59
+ const result = (0, index_1.executeTemplate)(data, path.join(process.cwd(), "/test.html"));
60
+ const htmlResult = (0, index_1.templateToString)(result.exports.default);
61
+ // Write to destination
62
+ // process.stdout.write( htmlResult );
63
+ (0, fs_1.writeFile)(outputFileName, htmlResult, {
64
+ encoding: "utf8",
65
+ flag: "w",
66
+ }, writeErr => {
67
+ if (!writeErr) {
68
+ console.log(`File is written: ${outputFileName}`);
69
+ }
70
+ else {
71
+ console.log(`Error writing to the output file ${outputFileName}`, writeErr);
72
+ }
73
+ });
74
+ }
75
+ else {
76
+ console.log(`Error reading the input file ${fileName}`, err);
77
+ }
78
+ });
@@ -0,0 +1,24 @@
1
+ import * as webpack from "webpack";
2
+ /**
3
+ * Webpack loader entry point for .tshtml files. Executes the template code and
4
+ * returns compiled HTML while registering file dependencies with webpack.
5
+ * @param this Loader context provided by webpack
6
+ * @param source Raw .tshtml source code
7
+ */
8
+ export default function (this: webpack.LoaderContext<any>, source: string): string;
9
+ /**
10
+ * Compile and execute a .tshtml template in an isolated VM context while
11
+ * tracking all file dependencies loaded via require().
12
+ * @param code Template source
13
+ * @param fileName Absolute path of the template file (used for resolution)
14
+ */
15
+ export declare function executeTemplate(code: string, fileName: string): {
16
+ exports: any;
17
+ dependencies: string[];
18
+ };
19
+ /**
20
+ * Convert different template builder outputs into a final HTML string.
21
+ * Accepts strings, class constructors (invoked), tshtml tags/arrays, or objects with toString().
22
+ */
23
+ export declare function templateToString(builder: any): string;
24
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,250 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.default = default_1;
37
+ exports.executeTemplate = executeTemplate;
38
+ exports.templateToString = templateToString;
39
+ const lodash_1 = require("lodash");
40
+ const ts_node_1 = require("ts-node");
41
+ const fs_1 = require("fs");
42
+ const path_1 = require("path");
43
+ const vm_1 = require("vm");
44
+ const webpack = __importStar(require("webpack"));
45
+ const tshtml_1 = require("tshtml");
46
+ const Module = require("module");
47
+ // ----------------------------------------------------------------------------------
48
+ // tshtml-loader implementation
49
+ /**
50
+ * Webpack loader entry point for .tshtml files. Executes the template code and
51
+ * returns compiled HTML while registering file dependencies with webpack.
52
+ * @param this Loader context provided by webpack
53
+ * @param source Raw .tshtml source code
54
+ */
55
+ function default_1(source) {
56
+ let result;
57
+ let htmlResult;
58
+ let builder;
59
+ try {
60
+ result = executeTemplate(source, this.resourcePath);
61
+ builder = result.exports.default;
62
+ }
63
+ catch (error) {
64
+ throw new Error(`Error executing template: ${error.message}\n ${error.stack}`);
65
+ }
66
+ if (builder == null) {
67
+ throw new Error(`Template must be exported as "default".`);
68
+ }
69
+ htmlResult = templateToString(builder);
70
+ // Dependencies
71
+ const reTestNodeFolder = /[\/\\]node_modules[\/\\]/;
72
+ const filteredDependencies = (0, lodash_1.filter)(result.dependencies, x => x.startsWith(this.rootContext) && !reTestNodeFolder.test(x));
73
+ for (let file of filteredDependencies) {
74
+ this.addDependency(file);
75
+ }
76
+ // In case of AOT build add the resulting HTML to the assets
77
+ if (this._compilation.name === "angular-compiler:resource") {
78
+ const compilation = this._compilation;
79
+ const rawRequest = this._module.rawRequest;
80
+ const request = rawRequest.substring(0, rawRequest.lastIndexOf("?"));
81
+ // postpone to a later event, because when loader is invoked, the chunks don't yet exist, and we need to register the file
82
+ compilation.hooks.processAssets.tap({
83
+ name: "tshtml-loader",
84
+ stage: webpack.Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS
85
+ }, (assets) => {
86
+ compilation.emitAsset(request, new webpack.sources.RawSource(htmlResult));
87
+ compilation.addChunk("resource").files.add(request);
88
+ });
89
+ }
90
+ return htmlResult;
91
+ }
92
+ // ----------------------------------------------------------------------------------
93
+ //
94
+ /**
95
+ * Compile and execute a .tshtml template in an isolated VM context while
96
+ * tracking all file dependencies loaded via require().
97
+ * @param code Template source
98
+ * @param fileName Absolute path of the template file (used for resolution)
99
+ */
100
+ function executeTemplate(code, fileName) {
101
+ const dirName = (0, path_1.dirname)(fileName);
102
+ const output = compileCode(code, fileName);
103
+ const script = new vm_1.Script(output, { filename: fileName });
104
+ const module = new Module(fileName);
105
+ module.filename = fileName;
106
+ module.loaded = true;
107
+ module.paths = Module._nodeModulePaths(dirName);
108
+ const req = createRequireService(fileName);
109
+ const sandbox = {
110
+ __filename: fileName,
111
+ __dirname: dirName,
112
+ module: module,
113
+ exports: module.exports,
114
+ require: req,
115
+ };
116
+ script.runInNewContext(sandbox, {
117
+ filename: fileName,
118
+ });
119
+ return {
120
+ exports: sandbox.exports,
121
+ dependencies: req.dependencies,
122
+ };
123
+ }
124
+ /**
125
+ * Convert different template builder outputs into a final HTML string.
126
+ * Accepts strings, class constructors (invoked), tshtml tags/arrays, or objects with toString().
127
+ */
128
+ function templateToString(builder) {
129
+ if (builder == null) {
130
+ return "";
131
+ }
132
+ else if ((0, lodash_1.isString)(builder)) {
133
+ return builder;
134
+ }
135
+ else if (typeof (builder) == "function") {
136
+ return (new builder()).toString();
137
+ }
138
+ else if ((0, lodash_1.isArray)(builder) || (0, tshtml_1.isTag)(builder)) {
139
+ return (0, tshtml_1.tagToString)(builder);
140
+ }
141
+ else {
142
+ return builder.toString();
143
+ }
144
+ }
145
+ let compilerService;
146
+ /***
147
+ * Compiles given TypeScript code
148
+ * @param code
149
+ * @param fileName
150
+ */
151
+ /**
152
+ * Compile TypeScript source using ts-node with Node16 settings.
153
+ * @param code Source code
154
+ * @param fileName File name used for source maps and module resolution
155
+ */
156
+ function compileCode(code, fileName) {
157
+ const tsFileName = `${fileName}.ts`;
158
+ if (compilerService == null) {
159
+ compilerService = (0, ts_node_1.register)({
160
+ compilerOptions: {
161
+ module: "Node16",
162
+ target: "es2022",
163
+ moduleResolution: "node16",
164
+ },
165
+ });
166
+ }
167
+ return compilerService.compile(code, tsFileName);
168
+ }
169
+ /***
170
+ * Create a logging wrapper for "require" function.
171
+ * @param fileName
172
+ */
173
+ /**
174
+ * Wrap Node's require to track dependency files and evict stale modules when underlying files change.
175
+ * @param fileName The template file being executed
176
+ */
177
+ function createRequireService(fileName) {
178
+ const req = Module.createRequire(fileName);
179
+ const cache = req.cache;
180
+ const dependencies = [];
181
+ const resolveFn = (id, options) => {
182
+ return req.resolve(id, options);
183
+ };
184
+ resolveFn.paths = req.resolve.paths;
185
+ const requireFn = (request) => {
186
+ let filePath;
187
+ try {
188
+ filePath = resolveFn(request);
189
+ }
190
+ catch (error) {
191
+ // Likely file doesn't exist, so short circuit to the default implementation
192
+ return req(request);
193
+ }
194
+ // Try to get the module from cache and check it's modification time
195
+ let module = cache[filePath];
196
+ if (module != null) {
197
+ cleanOutdatedModules(module, {});
198
+ }
199
+ const result = req(request);
200
+ // Store last modification date
201
+ const allFiles = {};
202
+ storeModuleTimes(cache[filePath], allFiles);
203
+ // Store request to the dependency resolution log
204
+ dependencies.push(...(0, lodash_1.keys)(allFiles));
205
+ return result;
206
+ };
207
+ requireFn.resolve = resolveFn;
208
+ requireFn.cache = cache;
209
+ requireFn.extensions = req.extensions;
210
+ requireFn.main = req.main;
211
+ requireFn.dependencies = dependencies;
212
+ return requireFn;
213
+ // ---
214
+ function cleanOutdatedModules(module, allFiles) {
215
+ allFiles[module.filename] = true;
216
+ let doClean = false;
217
+ // If the module file was modified since last access -> remove it from the cache
218
+ if (module.fileLastModified != null) {
219
+ const moduleTime = (0, fs_1.statSync)(module.filename).mtimeMs;
220
+ if (module.fileLastModified != moduleTime) {
221
+ doClean = true;
222
+ }
223
+ }
224
+ // Check if any child module is outdated
225
+ for (let childModule of module.children) {
226
+ if (allFiles[childModule.filename] || !checkFilename(childModule.filename))
227
+ continue;
228
+ doClean = cleanOutdatedModules(childModule, allFiles) || doClean;
229
+ }
230
+ if (doClean) {
231
+ delete cache[module.filename];
232
+ }
233
+ return doClean;
234
+ }
235
+ function storeModuleTimes(module, allFiles) {
236
+ allFiles[module.filename] = true;
237
+ if (module.fileLastModified == null) {
238
+ module.fileLastModified = (0, fs_1.statSync)(module.filename).mtimeMs;
239
+ }
240
+ let childModule;
241
+ for (childModule of module.children) {
242
+ if (allFiles[childModule.filename] || !checkFilename(childModule.filename))
243
+ continue;
244
+ storeModuleTimes(childModule, allFiles);
245
+ }
246
+ }
247
+ function checkFilename(filename) {
248
+ return filename.indexOf("\\node_modules\\") === -1;
249
+ }
250
+ }
package/package.json CHANGED
@@ -1,29 +1,56 @@
1
- {
2
- "name": "tshtml-loader",
3
- "version": "1.2.1",
4
- "description": "",
5
- "main": "lib/index.js",
6
- "files": [
7
- "lib/*.*"
8
- ],
9
- "bin": "./lib/export-template.js",
10
- "scripts": {
11
- "build": "tsc ./src/index.ts ./src/export-template.ts --outdir ./lib -d && npm run copy-docs",
12
- "build-watch": "tsc ./src/index.ts --outdir ./lib -d -w",
13
- "copy-docs": "npx npx shx cp ../README.md ."
14
- },
15
- "author": "LOGEX Group",
16
- "license": "MIT",
17
- "devDependencies": {
18
- "@types/lodash": "4.14.178",
19
- "@types/node": "16.11.7",
20
- "@types/webpack": "4.41.26"
21
- },
22
- "dependencies": {
23
- "lodash": "^4.17.21",
24
- "ts-node": "^10.5.0",
25
- "tsconfig-paths": "^3.12.0",
26
- "tshtml": "^1.1.6",
27
- "typescript": "4.3.5"
28
- }
29
- }
1
+ {
2
+ "name": "tshtml-loader",
3
+ "version": "1.4.3",
4
+ "description": "Webpack loader for tshtml template files",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/xorets/tshtml"
8
+ },
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts",
11
+ "files": [
12
+ "dist/**/*.js",
13
+ "dist/**/*.d.ts"
14
+ ],
15
+ "bin": "./dist/export-template.js",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "require": "./dist/index.js",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "publishConfig": {
25
+ "registry": "https://registry.npmjs.org/",
26
+ "access": "public"
27
+ },
28
+ "scripts": {
29
+ "build": "tsc --project . --outDir ./dist --module commonjs --declaration --declarationMap --skipLibCheck true",
30
+ "build-watch": "tsc --project . --outDir ./dist -d -w",
31
+ "pretest": "cd ../tshtml && npm run build --if-present",
32
+ "test": "tsx ./test/jasmine.js",
33
+ "coverage": "nyc tsx ./test/jasmine.js",
34
+ "prepublishOnly": "npm run test && npm run build"
35
+ },
36
+ "author": "LOGEX Group",
37
+ "license": "MIT",
38
+ "devDependencies": {
39
+ "@types/jasmine": "^5.1.15",
40
+ "@types/lodash": "4.17.23",
41
+ "@types/node": "25.0.9",
42
+ "@types/webpack": "5.28.5",
43
+ "jasmine": "6.0.0",
44
+ "nyc": "^17.1.0",
45
+ "tsx": "^4.21.0"
46
+ },
47
+ "dependencies": {
48
+ "lodash": "^4.17.21",
49
+ "ts-node": "^10.9.2",
50
+ "tshtml": "^1.4.3",
51
+ "typescript": "^5.9.3"
52
+ },
53
+ "overrides": {
54
+ "diff": "^8.0.3"
55
+ }
56
+ }
package/README.md DELETED
@@ -1,179 +0,0 @@
1
- # tshtml
2
-
3
- ## Installation
4
- ```
5
- npm i tshtml tshtml-loader
6
- ```
7
-
8
-
9
- ## What is it?
10
- tshtml-file is a TypeScript template that emits HTML code during build-time.
11
- The simplest one could look like this:
12
-
13
- ```
14
- // test.tshtml
15
-
16
- export default `<p>Hello world!</p>`;
17
- ```
18
- Obviosly this does not differ much from a static HTML file with the same paragraph.
19
- But now you can start write code in the template, just like this:
20
-
21
- ```
22
- export default `
23
- <p>Hello world!</p>
24
- <p>Build time is ${Date()}.</p>`;
25
- ```
26
-
27
- This code is executed at build time, and only the resulting
28
- HTML will be fed to Angular. This way we produce just the same fast Angular templates,
29
- but with help of possible very sophisticated code in tshtml.
30
- So, it's a lovely little metaprogramming: code that creates code.
31
-
32
- You can write helper functions to extract repetitive patterns of template code,
33
- import constants and static data structures used at run time to generate some
34
- template elements out of them, and also create templates that inherit other templates.
35
- The latter is very handy when you have Angular components derived from some
36
- base components.
37
-
38
- ## _html_ function
39
- Combining HTML by hands is not very pleasant task. You must ensure that it is well-formed
40
- so usually it requires more efforts than just to concatenate strings together.
41
-
42
- To simplify this task we created `html` function. It parses the text into a
43
- tree of node-like objects that can be later serialized to a well-formed HTML.
44
- Since the tree is just a graph of plain JavaScript objects, you can update it:
45
- change attributes, add new children and so on.
46
-
47
- The simplest example with `html` added looks basically the same:
48
- ```
49
- import { html } from "tshtml";
50
-
51
- export default html`<p>Hello world!</p>`;
52
- ```
53
-
54
- Let's combine two HTML trees together:
55
- ```
56
- import { html } from "tshtml";
57
-
58
- const buildTime = html`<p>Build time is ${Date()}.</p>`;
59
-
60
- // Resulting tree has buildTime subtree inserted at the appropriate place
61
- const res = html`
62
- <p>Hello world!</p>
63
- ${buildTime}`;
64
-
65
- // Tree of template elements will be converted to string by the loader
66
- export default res;
67
- ```
68
-
69
- Here `builtTime` is not a string, it's an object, but you can still use standard
70
- template string placeholder syntax to combine HTML fragments together.
71
-
72
- The tree can be manipulated using methods of `TemplateItem` class.
73
- ```
74
- import { htmlEl } from "tshtml";
75
-
76
- const res = htmlEl`<p>Hello world!</p>`;
77
-
78
- // Add an attribute
79
- res.attrs( { "color": "red } );
80
-
81
- export default res;
82
- ```
83
-
84
- ## To use in your Angular project
85
- First, configure Angular build as described here:
86
- https://codeburst.io/customizing-angular-cli-6-build-an-alternative-to-ng-eject-a48304cd3b21
87
-
88
- For that you need to install necessary packages:
89
- ```
90
- npm install @angular-devkit/build-angular --save-dev
91
- npm install @angular-builders/custom-webpack --save-dev
92
- ```
93
- Add "architect" section to the "angular.json" if it is not already there. Change
94
- builder configuration and specify the name of additional webpack config file:
95
- ```
96
- "architect": {
97
- "build": {
98
- "builder": "@angular-builders/custom-webpack:browser",
99
- "options": {
100
- "customWebpackConfig": {
101
- "path": "./extra-webpack.config.js",
102
- "replaceDuplicatePlugins": true
103
- },
104
- ...
105
- },
106
- "serve": {
107
- "builder": "@angular-builders/custom-webpack:dev-server",
108
- ...
109
- ```
110
-
111
- Add `extra-webpack.config.js`. Configuration is a bit different depending of which
112
- Webpack version do you use.
113
-
114
- **Webpack 4**
115
-
116
- With Webpack 4 (used in Angular 11 and earlier) you need to configure loader like this.
117
- It's preferred to use `tshtml-loader` version less than 1.2 with Webpack 4.
118
- ```
119
- module.exports = {
120
- module: {
121
- rules: [
122
- {
123
- test: /\.tshtml$/,
124
- use: ["tshtml-loader"],
125
- enforce: "pre"
126
- },
127
- ]
128
- }
129
- };
130
- ```
131
-
132
-
133
- **Webpack 5**
134
-
135
- Webpack 5 (used in Angular 12 and up) brings new resource types, so the recommended loader configuration is the following:
136
- ```
137
- module.exports = {
138
- module: {
139
- rules: [
140
- test: /\.tshtml$/,
141
- use: ["tshtml-loader"],
142
- type: "asset/source"
143
- ]
144
- }
145
- };
146
- ```
147
-
148
-
149
- You also need to have "tshtml" and "tshtml-loader" packages in your project.
150
-
151
- Finally you just refer to `tshtml` files instead of `html` files in your Angular components.
152
-
153
-
154
- ## Library development
155
-
156
- In tshtml folder:
157
- ```
158
- npm run test
159
- npm run build
160
- ```
161
-
162
- ### Debugging
163
-
164
- If you need to debug the tests, then you can do the following:
165
-
166
- 1. In the console where you are going to execute tests set environment variable:
167
- `set-item env:NODE_OPTIONS "--inspect"`
168
-
169
- 1. Configure you debugger to attach to Node.js at port 9229. Start the debugger
170
-
171
- 1. Start test: `node ./test/jasmine "TEST NAME"`
172
-
173
- ### tshtml-loader
174
-
175
- In tshtml-loader folder:
176
- ```
177
- npm run build
178
- ```
179
-
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
@@ -1,42 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- exports.__esModule = true;
4
- var fs_1 = require("fs");
5
- var path = require("node:path");
6
- var index_1 = require("./index");
7
- // ----------------------------------------------------------------------------------
8
- if (process.argv.length !== 3) {
9
- console.error("Please specify one .tshtml file");
10
- process.exit();
11
- }
12
- var fileName = process.argv[2];
13
- var extension = path.extname(fileName).toLowerCase();
14
- if (extension !== ".tshtml") {
15
- console.error("Input file must have .tshtml extension");
16
- process.exit();
17
- }
18
- var fileNameNoExtension = fileName.substr(0, fileName.length - extension.length);
19
- var outputFileName = fileNameNoExtension + ".html";
20
- fs_1.readFile(fileName, { encoding: 'utf-8' }, function (err, data) {
21
- if (!err) {
22
- // Transform the source
23
- var result = index_1.executeTemplate(data, path.join(process.cwd(), "/test.html"));
24
- var htmlResult = index_1.templateToString(result.exports["default"]);
25
- // Write to destination
26
- // process.stdout.write( htmlResult );
27
- fs_1.writeFile(outputFileName, htmlResult, {
28
- encoding: "utf8",
29
- flag: "w"
30
- }, function (writeErr) {
31
- if (!writeErr) {
32
- console.log("File is written: " + outputFileName);
33
- }
34
- else {
35
- console.log("Error writing to the output file " + outputFileName, writeErr);
36
- }
37
- });
38
- }
39
- else {
40
- console.log("Error reading the input file " + fileName, err);
41
- }
42
- });
package/lib/index.d.ts DELETED
@@ -1,8 +0,0 @@
1
- import LoaderContext = webpack.loader.LoaderContext;
2
- import * as webpack from "webpack";
3
- export default function (this: LoaderContext, source: string): string;
4
- export declare function executeTemplate(code: string, fileName: string): {
5
- exports: any;
6
- dependencies: string[];
7
- };
8
- export declare function templateToString(builder: any): string;
package/lib/index.js DELETED
@@ -1,180 +0,0 @@
1
- "use strict";
2
- exports.__esModule = true;
3
- exports.templateToString = exports.executeTemplate = void 0;
4
- var lodash_1 = require("lodash");
5
- var ts_node_1 = require("ts-node");
6
- var fs_1 = require("fs");
7
- var path_1 = require("path");
8
- var vm_1 = require("vm");
9
- var tshtml_1 = require("tshtml");
10
- require("tsconfig-paths/register"); // Necessary to support @folders resolution by Nodejs
11
- var Module = require("module");
12
- // ----------------------------------------------------------------------------------
13
- //
14
- function default_1(source) {
15
- var _this = this;
16
- var result;
17
- var htmlResult;
18
- var builder;
19
- try {
20
- result = executeTemplate(source, this.resourcePath);
21
- builder = result.exports["default"];
22
- }
23
- catch (error) {
24
- throw new Error("Error executing template: " + error.message + "\n " + error.stack);
25
- }
26
- if (builder == null) {
27
- throw new Error("Template must be exported as \"default\".");
28
- }
29
- htmlResult = templateToString(builder);
30
- // Dependencies
31
- var reTestNodeFolder = /[\/\\]node_modules[\/\\]/g;
32
- var filteredDependencies = lodash_1.filter(result.dependencies, function (x) { return x.startsWith(_this.rootContext) && !reTestNodeFolder.test(x); });
33
- for (var _i = 0, filteredDependencies_1 = filteredDependencies; _i < filteredDependencies_1.length; _i++) {
34
- var file = filteredDependencies_1[_i];
35
- this.addDependency(file);
36
- }
37
- return htmlResult;
38
- }
39
- exports["default"] = default_1;
40
- ;
41
- // ----------------------------------------------------------------------------------
42
- //
43
- function executeTemplate(code, fileName) {
44
- var dirName = path_1.dirname(fileName);
45
- var output = compileCode(code, fileName);
46
- var script = new vm_1.Script(output, { filename: fileName });
47
- var module = new Module(fileName);
48
- module.filename = fileName;
49
- module.loaded = true;
50
- module.paths = Module._nodeModulePaths(dirName);
51
- var req = createRequireService(fileName);
52
- var sandbox = {
53
- __filename: fileName,
54
- __dirname: dirName,
55
- module: module,
56
- exports: module.exports,
57
- require: req
58
- };
59
- script.runInNewContext(sandbox, {
60
- filename: fileName
61
- });
62
- return {
63
- exports: sandbox.exports,
64
- dependencies: req.dependencies
65
- };
66
- }
67
- exports.executeTemplate = executeTemplate;
68
- function templateToString(builder) {
69
- if (lodash_1.isString(builder)) {
70
- return builder;
71
- }
72
- else if (typeof (builder) == "function") {
73
- return (new builder()).toString();
74
- }
75
- else if (lodash_1.isArray(builder) || tshtml_1.isTag(builder)) {
76
- return tshtml_1.tagToString(builder);
77
- }
78
- else {
79
- return builder.toString();
80
- }
81
- }
82
- exports.templateToString = templateToString;
83
- var compilerService;
84
- /***
85
- * Compiles given TypeScript code
86
- * @param code
87
- * @param fileName
88
- */
89
- function compileCode(code, fileName) {
90
- var tsFileName = fileName + ".ts";
91
- if (compilerService == null) {
92
- compilerService = ts_node_1.register({
93
- compilerOptions: {
94
- module: "CommonJS",
95
- target: "es2015"
96
- }
97
- });
98
- }
99
- return compilerService.compile(code, tsFileName);
100
- }
101
- /***
102
- * Create a logging wrapper for "require" function.
103
- * @param fileName
104
- */
105
- function createRequireService(fileName) {
106
- var req = Module.createRequire(fileName);
107
- var cache = req.cache;
108
- var dependencies = [];
109
- var resolveFn = function (id, options) {
110
- return req.resolve(id, options);
111
- };
112
- resolveFn.paths = req.resolve.paths;
113
- var requireFn = function (request) {
114
- var filePath;
115
- try {
116
- filePath = resolveFn(request);
117
- }
118
- catch (error) {
119
- // Likely file doesn't exist, so short circuit to the default implementation
120
- return req(request);
121
- }
122
- // Try to get the module from cache and check it's modification time
123
- var module = cache[filePath];
124
- if (module != null) {
125
- cleanOutdatedModules(module, {});
126
- }
127
- var result = req(request);
128
- // Store last modification date
129
- var allFiles = {};
130
- storeModuleTimes(cache[filePath], allFiles);
131
- // Store request to the dependency resolution log
132
- dependencies.push.apply(dependencies, lodash_1.keys(allFiles));
133
- return result;
134
- };
135
- requireFn.resolve = resolveFn;
136
- requireFn.cache = cache;
137
- requireFn.extensions = req.extensions;
138
- requireFn.main = req.main;
139
- requireFn.dependencies = dependencies;
140
- return requireFn;
141
- // ---
142
- function cleanOutdatedModules(module, allFiles) {
143
- allFiles[module.filename] = true;
144
- var doClean = false;
145
- // If the module file was modified since last access -> remove it from the cache
146
- if (module.fileLastModified != null) {
147
- var moduleTime = fs_1.statSync(module.filename).mtimeMs;
148
- if (module.fileLastModified != moduleTime) {
149
- doClean = true;
150
- }
151
- }
152
- // Check if any child module is outdated
153
- for (var _i = 0, _a = module.children; _i < _a.length; _i++) {
154
- var childModule = _a[_i];
155
- if (allFiles[childModule.filename] || !checkFilename(childModule.filename))
156
- continue;
157
- doClean = cleanOutdatedModules(childModule, allFiles) || doClean;
158
- }
159
- if (doClean) {
160
- delete cache[module.filename];
161
- }
162
- return doClean;
163
- }
164
- function storeModuleTimes(module, allFiles) {
165
- allFiles[module.filename] = true;
166
- if (module.fileLastModified == null) {
167
- module.fileLastModified = fs_1.statSync(module.filename).mtimeMs;
168
- }
169
- var childModule;
170
- for (var _i = 0, _a = module.children; _i < _a.length; _i++) {
171
- childModule = _a[_i];
172
- if (allFiles[childModule.filename] || !checkFilename(childModule.filename))
173
- continue;
174
- storeModuleTimes(childModule, allFiles);
175
- }
176
- }
177
- function checkFilename(filename) {
178
- return filename.indexOf("\\node_modules\\") === -1;
179
- }
180
- }