@dryfeld/nunjucks-loader 4.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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Ben Daley
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.
22
+
package/index.js ADDED
@@ -0,0 +1,154 @@
1
+ /*******************************************************************
2
+ *
3
+ * This module was heavily inspired by nunjucksify.
4
+ * (https://www.npmjs.com/package/nunjucksify)
5
+ *
6
+ * Full credit to the original authors.
7
+ *
8
+ ******************************************************************/
9
+
10
+ const nunjucks = require('nunjucks');
11
+ const path = require('path');
12
+ let hasRun = false;
13
+ let env;
14
+ let pathToConfigure;
15
+ let jinjaCompatStr;
16
+ let root;
17
+
18
+ module.exports = function (source) {
19
+ if (this.target !== 'web') {
20
+ throw new Error('[nunjucks-loader] non-web targets are not supported');
21
+ }
22
+
23
+ this.cacheable();
24
+
25
+ let envOpts;
26
+
27
+ if (!hasRun) {
28
+ const query = new URLSearchParams(this.query);
29
+ envOpts = query.opts || {};
30
+ if (query){
31
+
32
+ env = new nunjucks.Environment([], envOpts);
33
+
34
+ if (query.config){
35
+ pathToConfigure = query.config;
36
+ try {
37
+ const configure = require(query.config);
38
+ configure(env);
39
+ }
40
+ catch (e) {
41
+ if (e.code === 'MODULE_NOT_FOUND') {
42
+ if (!query.quiet) {
43
+ const message = 'Cannot configure nunjucks environment before precompile\n' +
44
+ '\t' + e.message + '\n' +
45
+ 'Async filters and custom extensions are unsupported when the nunjucks\n' +
46
+ 'environment configuration depends on webpack loaders or custom module\n' +
47
+ 'resolve rules. If you are not using async filters or custom extensions\n' +
48
+ 'with nunjucks, you can safely ignore this warning.'
49
+ ;
50
+ this.emitWarning(message);
51
+ }
52
+ }
53
+ else {
54
+ this.emitError(e.message);
55
+ }
56
+ }
57
+ }
58
+
59
+ // Specify the template search path, so we know from what directory
60
+ // it should be relative to.
61
+ if (query.root) {
62
+ root = query.root;
63
+ }
64
+
65
+ // Enable experimental Jinja compatibility to be enabled
66
+ if(query.jinjaCompat){
67
+ jinjaCompatStr = 'nunjucks.installJinjaCompat();\n';
68
+ }
69
+ }
70
+ else {
71
+ env = new nunjucks.Environment([]);
72
+ }
73
+ hasRun = true;
74
+ }
75
+
76
+ const name = path.relative(root || this.rootContext || this.options.context, this.resourcePath);
77
+
78
+ let nunjucksCompiledStr = nunjucks.precompileString(source, {
79
+ env: env,
80
+ name: name
81
+ });
82
+
83
+ nunjucksCompiledStr = nunjucksCompiledStr.replace(/window\.nunjucksPrecompiled/g, 'nunjucks.nunjucksPrecompiled');
84
+
85
+ // ==============================================================================
86
+ // replace 'require' filter with a webpack require expression (to resolve assets)
87
+ // ==============================================================================
88
+ const filterReg = /env\.getFilter\(\"require\"\)\.call\(context, \"(.*?)\"/g;
89
+ nunjucksCompiledStr = nunjucksCompiledStr.replace(filterReg, 'require("$1"');
90
+
91
+ // ================================================================
92
+ // Begin to write the compiled template output to return to webpack
93
+ // ================================================================
94
+ let compiledTemplate = '';
95
+ compiledTemplate += 'var nunjucks = require("nunjucks/browser/nunjucks-slim");\n';
96
+ if (jinjaCompatStr) {
97
+ compiledTemplate += jinjaCompatStr + '\n';
98
+ }
99
+ compiledTemplate += 'var env;\n';
100
+ compiledTemplate += 'if (!nunjucks.currentEnv){\n';
101
+ compiledTemplate += '\tenv = nunjucks.currentEnv = new nunjucks.Environment([], ' + JSON.stringify(envOpts) + ');\n';
102
+ compiledTemplate += '} else {\n';
103
+ compiledTemplate += '\tenv = nunjucks.currentEnv;\n';
104
+ compiledTemplate += '}\n';
105
+ if (pathToConfigure) {
106
+ compiledTemplate += 'var configure = require("' + path.relative(this.context, pathToConfigure) + '")(env);\n';
107
+ }
108
+
109
+
110
+
111
+
112
+ // =========================================================================
113
+ // Find template dependencies within nunjucks (extends, import, include etc)
114
+ // =========================================================================
115
+ //
116
+ // Create an object on nunjucks to hold the template dependencies so that they persist
117
+ // when this loader compiles multiple templates.
118
+ compiledTemplate += 'var dependencies = nunjucks.webpackDependencies || (nunjucks.webpackDependencies = {});\n';
119
+
120
+ const templateReg = /env\.getTemplate\(\"(.*?)\"/g;
121
+ let match;
122
+
123
+ // Create an object to store references to the dependencies that have been included - this ensures that a template
124
+ // dependency is only written once per file, even if it is used multiple times.
125
+ const required = {};
126
+
127
+ // Iterate over the template dependencies
128
+ while (match = templateReg.exec(nunjucksCompiledStr)) {
129
+ const templateRef = match[1];
130
+ if (!required[templateRef]) {
131
+ // Require the dependency by name, so it gets bundled by webpack
132
+ compiledTemplate += 'dependencies["' + templateRef + '"] = require( "' + templateRef + '" );\n';
133
+ required[templateRef] = true;
134
+ }
135
+ }
136
+
137
+
138
+
139
+ compiledTemplate += '\n\n\n\n';
140
+
141
+ // Include a shim module (by reference rather than inline) that modifies the nunjucks runtime to work with the loader.
142
+ compiledTemplate += 'var shim = require("' + path.resolve(this.context, __dirname + '/runtime-shim') + '");\n';
143
+ compiledTemplate += '\n\n';
144
+
145
+ // Write the compiled template string
146
+ compiledTemplate += nunjucksCompiledStr + '\n';
147
+
148
+ compiledTemplate += '\n\n';
149
+
150
+ // export the shimmed module
151
+ compiledTemplate += 'module.exports = shim(nunjucks, env, nunjucks.nunjucksPrecompiled["' + name + '"] , dependencies)';
152
+
153
+ return compiledTemplate;
154
+ };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@dryfeld/nunjucks-loader",
3
+ "version": "4.0.0",
4
+ "description": "A nunjucks loader for webpack.",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "webpack-dev-server --config test/webpack.config.js"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git://github.com/at0g/nunjucks-loader.git"
12
+ },
13
+ "keywords": [
14
+ "webpack",
15
+ "nunjucks",
16
+ "nunj",
17
+ "loader",
18
+ "template"
19
+ ],
20
+ "author": "Ben Daley <ben@fanboy.io>",
21
+ "license": "MIT",
22
+ "bugs": {
23
+ "url": "https://github.com/at0g/nunjucks-loader/issues"
24
+ },
25
+ "homepage": "https://github.com/at0g/nunjucks-loader",
26
+ "peerDependencies": {
27
+ "nunjucks": ">= 2.5.0 <= 4.0.0"
28
+ },
29
+ "devDependencies": {
30
+ "chai": "^5.1.0",
31
+ "mocha-loader": "^5.1.5",
32
+ "nunjucks": "^3.2.4",
33
+ "raw-loader": "^4.0.2",
34
+ "slash": "^5.1.0",
35
+ "webpack": "^5.90.3",
36
+ "webpack-cli": "^5.1.4",
37
+ "webpack-dev-server": "^5.0.2"
38
+ }
39
+ }
package/readme.md ADDED
@@ -0,0 +1,236 @@
1
+ # Nunjucks loader for webpack
2
+
3
+ - `require` precompiled templates in webpack
4
+ - supports `extends` and `include`
5
+ - resolves template dependencies using `require`
6
+ - bundles the nunjucks-slim browser runtime
7
+ - use the version of nunjucks you want to as a peer dependency
8
+ - supports experimental Jinja compatibility
9
+
10
+ ## Usage
11
+
12
+ [Documentation: Using loaders](http://webpack.github.io/docs/using-loaders.html)
13
+
14
+ ### Recommended configuration
15
+
16
+ Install: `npm install nunjucks-loader --save`
17
+
18
+ Add to webpack.config to process all .njk and .nunjucks files:
19
+
20
+ ``` javascript
21
+ // file: webpack.config.js
22
+ module.exports = {
23
+
24
+ entry: './src/entry.js',
25
+
26
+ output: {
27
+ path: __dirname,
28
+ filename: 'bundle.js'
29
+ },
30
+
31
+ module: {
32
+ loaders: [
33
+ {
34
+ test: /\.(njk|nunjucks)$/,
35
+ loader: 'nunjucks-loader'
36
+ }
37
+ ]
38
+ }
39
+
40
+ };
41
+ ```
42
+
43
+ Then use it in your module code without the `nunjucks!` prefix:
44
+
45
+ ``` javascript
46
+ // file: src/entry.js
47
+ var tpl = require('./views/page.njk');
48
+ var html = tpl.render({ message: 'Foo that!' });
49
+ ```
50
+
51
+ #### Inline configuration (not recommended)
52
+
53
+ If using the inline configuration (below), references inside of templates to other files (parents, imports etc) may not
54
+ resolve correctly - hence it's preferable to use the webpack.config method above.
55
+
56
+ ``` javascript
57
+ var tpl = require("nunjucks!./views/page.njk");
58
+ var html = tpl.render({ message: 'Foo that!' });
59
+ ```
60
+
61
+
62
+ ### webpack.target = 'node'
63
+
64
+ **The 2.x versions of this loader do not support node/UMD bundles.**
65
+
66
+ If you need to support node or UMD with the bundle, the 1.x version (`npm install nunjucks-loader@1.0.7`) supports these
67
+ targets.
68
+
69
+
70
+
71
+ ### Filters and extensions
72
+
73
+ A *require* filter is added by this package that allows you to use webpack to resolve file references.
74
+ Eg.
75
+
76
+ ```
77
+ {# use the raw-loader to replace 'readme.txt' with the contents of that file #}
78
+ {{ 'raw!readme.txt' | require }}
79
+ ```
80
+
81
+
82
+ A custom nunjucks.Environment is used by the loader, to configure the nunjucks environment:
83
+
84
+ - To pass [nunjucks.Environment options](https://mozilla.github.io/nunjucks/api.html#environment), add a `opts` key to
85
+ the nunjucks loader query in webpack.config.js
86
+ - Create a file that will configure the environment. This should export a function that receives the nunjucks
87
+ environment as its first argument.
88
+ - Add a `config` key to the nunjucks-loader query in webpack.config.js
89
+ - Add an optional `quiet` key to the loader query in webpack.config.js to suppress precompile warnings (see below)
90
+
91
+ ``` javascript
92
+ // file: src/nunjucks.config.js
93
+ module.exports = function(env){
94
+
95
+ env.addFilter('asyncFoo', function(input, done){
96
+ setTimeout(function(){
97
+ done('[asyncFoo] ' + input);
98
+ }, 1000)
99
+ }, true);
100
+
101
+ // env.addExtension(...) etc
102
+ }
103
+
104
+ // file: webpack.config.js
105
+ module.exports = {
106
+
107
+ entry: './src/entry.js',
108
+
109
+ output: {
110
+ path: __dirname,
111
+ filename: 'bundle.js'
112
+ },
113
+
114
+ module: {
115
+ loaders: [
116
+ {
117
+ test: /\.(njk|nunjucks)$/,
118
+ loader: 'nunjucks-loader',
119
+ query: {
120
+ config: __dirname + '/src/nunjucks.config.js'
121
+ }
122
+ }
123
+ ]
124
+ }
125
+ };
126
+
127
+ ```
128
+
129
+ __If using async filters or custom extensions with nunjucks__, they must be available before the template is precompiled.
130
+ If the nunjucks config file depends on webpack resolve (such as loaders or custom module paths), the custom
131
+ filters/extensions will not be available at precompile time. When/if this happens, you will receive the following
132
+ warning in the console:
133
+
134
+ *Cannot configure nunjucks environment before precompile*
135
+
136
+ When using webpack resolve with the environment config and __not__ using async filters or custom extensions, the warning
137
+ can be safely ignored - standard filters are still added to the environment at runtime.
138
+
139
+ To remove the warning, pass the `quiet` option in the loader query. eg:
140
+
141
+ ```
142
+ // file: webpack.config.js
143
+ module.exports = {
144
+
145
+ module: {
146
+ loaders: [
147
+ {
148
+ test: /\.(njk|nunjucks)$/,
149
+ loader: 'nunjucks-loader',
150
+ query: {
151
+ config: __dirname + '/src/nunjucks.config.js',
152
+ quiet: true // Don't show the 'Cannot configure nunjucks environment before precompile' warning
153
+ }
154
+ }
155
+ ]
156
+ }
157
+ };
158
+ ```
159
+
160
+
161
+
162
+
163
+ ## Path resolution
164
+
165
+ This loader modifies the way nunjucks resolves dependencies (eg `extends`, `import` and `include`) to work correctly
166
+ with webpack. As a result, you may use `require` style relative paths in your templates.
167
+ Add a `resolve.root` key to `webpack.config.js` to resolve your templates without using relative paths.
168
+
169
+
170
+ ``` javascript
171
+ // file: webpack.config.js
172
+ module.exports = {
173
+ resolve: {
174
+ root: [
175
+ __dirname,
176
+ __dirname + '/src/views' // Resolve templates to ./src/views
177
+ ]
178
+ }
179
+ }
180
+ ```
181
+
182
+ Alternatively, a `root` query parameter can be passed to the loader to set the root template directory.
183
+
184
+ ``` javascript
185
+ // webpack.config.js
186
+ module.exports = {
187
+ module: {
188
+ loaders: [
189
+ {
190
+ test: /\.(nunj|nunjucks)$/,
191
+ loader: 'nunjucks-loader',
192
+ query: {
193
+ root: __dirname + '/path/to/templates'
194
+ }
195
+ }
196
+ ]
197
+ }
198
+ }
199
+ ```
200
+
201
+
202
+ ## Jinja/Python compatibility
203
+
204
+ If [experimental support for Jinja compatibility](https://mozilla.github.io/nunjucks/api.html#installjinjacompat)
205
+ is desired, pass the jinjaCompat option in the loader query. eg:
206
+
207
+ ```
208
+ // file: webpack.config.js
209
+ module.exports = {
210
+
211
+ module: {
212
+ loaders: [
213
+ {
214
+ test: /\.(nunj|nunjucks)$/,
215
+ loader: 'nunjucks-loader',
216
+ query: {
217
+ jinjaCompat: true
218
+ }
219
+ }
220
+ ]
221
+ }
222
+ };
223
+ ```
224
+
225
+ This option will not provide full Jinja/Python compatibility, but will treat `True`/`False` like `true`/`false`, and
226
+ augment arrays and objects with Python-style methods (such as `count`, `find`, `insert`, `get`, and `update`).
227
+ Review the [jinja-compat source](https://github.com/mozilla/nunjucks/blob/master/src/jinja-compat.js) to see
228
+ everything it adds.
229
+
230
+
231
+
232
+
233
+ ## Tests
234
+
235
+ `npm run test`
236
+ Navigate to http://localhost:8080/test
@@ -0,0 +1,46 @@
1
+ module.exports = function (nunjucks, env, obj, dependencies){
2
+
3
+ const oldRoot = obj.root;
4
+
5
+ obj.root = function( env, context, frame, runtime, ignoreMissing, cb ) {
6
+ const oldGetTemplate = env.getTemplate;
7
+ env.getTemplate = function (name, ec, parentName, ignoreMissing, cb) {
8
+ if( typeof ec === "function" ) {
9
+ cb = ec = false;
10
+ }
11
+ const _require = function (name) {
12
+ try {
13
+ // add a reference to the already resolved dependency here
14
+ return dependencies[name];
15
+ }
16
+ catch (e) {
17
+ if (frame.get("_require")) {
18
+ return frame.get("_require")(name);
19
+ }
20
+ else {
21
+ console.warn('Could not load template "%s"', name);
22
+ }
23
+ }
24
+ };
25
+
26
+ const tmpl = _require(name);
27
+ frame.set("_require", _require);
28
+
29
+ if( ec ) tmpl.compile();
30
+ cb( null, tmpl );
31
+ };
32
+
33
+ oldRoot(env, context, frame, runtime, ignoreMissing, function (err, res) {
34
+ env.getTemplate = oldGetTemplate;
35
+ cb( err, res );
36
+ });
37
+ };
38
+
39
+ const src = {
40
+ obj: obj,
41
+ type: 'code'
42
+ };
43
+
44
+ return new nunjucks.Template(src, env);
45
+
46
+ };