瀏覽代碼

Added template-comment-loader to the snippetAdapter webpack configuration.

Maciej Bukowski 6 年之前
父節點
當前提交
612e6972db
共有 2 個文件被更改,包括 45 次插入2 次删除
  1. 8 2
      scripts/docs/snippetadapter.js
  2. 37 0
      scripts/docs/template-comment-loader.js

+ 8 - 2
scripts/docs/snippetadapter.js

@@ -27,7 +27,8 @@ module.exports = function snippetAdapter( data ) {
 		entry: data.snippetSource.js,
 		outputPath,
 		language: snippetConfig.language,
-		production: data.options.production
+		production: data.options.production,
+		templateCommentLoaderConfig: data.options.templateCommentLoaderConfig || {}
 	} );
 
 	let promise;
@@ -151,7 +152,12 @@ function getWebpackConfig( config ) {
 							} )
 						}
 					]
-				}
+				},
+				{
+					test: /\.js$/,
+					loader: require.resolve( './template-comment-loader' ),
+					query: config.templateCommentLoaderConfig
+				},
 			]
 		}
 	};

+ 37 - 0
scripts/docs/template-comment-loader.js

@@ -0,0 +1,37 @@
+/**
+ * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* eslint-env node */
+
+/*
+ * Matches `// @if param // someCode` and evaluates the `option.param`.
+ * If the param is evaluated to true, then uncomments the code.
+ *
+ * Note: Use this only for conditional imports. Otherwise use the webpack define plugin.
+ */
+module.exports = function templateCommentLoader( source, map ) {
+	source = source.replace( /\/\/ @if (!?[\w]+) \/\/(.+)/g, ( match, option, body ) => {
+		// this.query comes from the webpack loader config.
+		// Missing param in webpack loader config
+		if ( !( option in this.query ) ) {
+			return match;
+		}
+
+		const optionValue = this.query[ option ];
+
+		// Do nothing when the option is falsy
+		if ( !optionValue ) {
+			return match;
+		}
+
+		// Replace the option in body with evaluated value.
+		body = body.replace( new RegExp( option, 'g' ), this.query[ option ] );
+
+		// Uncomment the following code otherwise.
+		return `/* @if ${ option } */ ${ body }`;
+	} );
+
+	this.callback( null, source, map );
+};