Ejemplo n.º 1
0
		/// <summary>
		/// Creates and returns the appropriate arguments list for the webpack based on the provided options
		/// </summary>
		public static string GetWebpackArguments(string rootPath, WebpackOptions options) {
			var result = new StringBuilder(DefaultDevFile);
			if (options.HandleStyles && options.StylesTypes.Any()) {
				if (options.StylesTypes.Contains(StylesType.Css)) {
					result.Append(CssFiles);
				}
				if (options.StylesTypes.Contains(StylesType.Sass)) {
					result.Append(SassFiles);
				}
				if (options.StylesTypes.Contains(StylesType.Less)) {
					result.Append(LessFiles);
				}
			}
			if(options.HandleStaticFiles) {
				options.StaticFileTypes.ToList().ForEach(staticFileType => {
					result.Append(string.Format(StaticFile, staticFileType.ToString().ToLowerInvariant(), options.StaticFileTypesLimit));
				});
			}
			result.Append($"--entry ./{options.EntryPoint} ");
			result.Append($"--output-path {rootPath} ");
			result.Append($"--output-filename {options.OutputFileName} ");

			if(options.EnableHotLoading) {
				result.Append("--hot --inline ");
				result.Append($"--host {options.DevServerOptions.Host} ");
				result.Append($"--port {options.DevServerOptions.Port} ");
				result.Append($"--output-public-path http://{options.DevServerOptions.Host}:{options.DevServerOptions.Port}/ ");
			}

			return result.ToString();
		}
Ejemplo n.º 2
0
		public WebPackMiddlewareOptions Execute(WebpackOptions options) {
			var toolToExecute = options.EnableHotLoading ? webpackDevServer : webpack;
			var logger = _loggerFactory.CreateLogger(toolToExecute);

			logger.LogInformation($"Verifying required tools are installed");
			EnsuereNodeModluesInstalled(options.EnableHotLoading, logger);
			logger.LogInformation($"All node modules are properly installed");

			CreateWebpackConfigurationFile(options);

			logger.LogInformation($"{toolToExecute} Execution started");
			var arguments = ArgumentsHelper.GetWebpackArguments(_webRootPath, options);
			logger.LogInformation($"{toolToExecute} is called with these arguments: {arguments}");
			Process process = new Process();
			process.StartInfo = new ProcessStartInfo() {
				FileName = GetNodeExecutable(toolToExecute),
				Arguments = arguments,
				UseShellExecute = false
			};
			process.Start();
			logger.LogInformation($"{toolToExecute} started successfully");

			return new WebPackMiddlewareOptions {
				EnableHotLoading = options.EnableHotLoading,
				OutputFileName = options.OutputFileName,
				Host = options.DevServerOptions.Host,
				Port = options.DevServerOptions.Port
			};
		}
        /// <summary>
        /// Adds webpack functionality to the application. It should be used only in development environment.
        /// This method does not require an external configuration file and covers the most usual cases for webpack.
        /// Based on the provided <paramref name="options"/> the underlying middleware will add the required script tags
        /// so there is not need to add them manually.
        /// </summary>
        public static IApplicationBuilder UseWebpack(this IApplicationBuilder app, WebpackOptions options)
        {
            var webpack           = app.ApplicationServices.GetService <IWebpack>();
            var middleWareOptions = webpack.Execute(options);

            app.UseMiddleware <WebpackMiddleware>(middleWareOptions);
            return(app);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates and returns the appropriate arguments list for the webpack based on the provided options
        /// </summary>
        public static string GetWebpackArguments(string rootPath, WebpackOptions options, bool includeDefaultConfigFile)
        {
            var result = new StringBuilder();

            if (includeDefaultConfigFile)
            {
                result.Append(DefaultDevFile);
            }
            if (options.HandleStyles && options.StylesTypes.Any())
            {
                if (options.StylesTypes.Contains(StylesType.Css))
                {
                    result.Append(CssFiles);
                }
                if (options.StylesTypes.Contains(StylesType.Sass))
                {
                    result.Append(SassFiles);
                }
                if (options.StylesTypes.Contains(StylesType.Less))
                {
                    result.Append(LessFiles);
                }
            }
            if (options.HandleAngularTemplates)
            {
                result.Append(HandleAngularTemplateFiles);
            }
            if (options.HandleStaticFiles)
            {
                options.StaticFileTypes.ToList().ForEach(staticFileType => {
                    result.Append(string.Format(StaticFile, staticFileType.ToString().ToLowerInvariant(), options.StaticFileTypesLimit));
                });
            }
            result.Append($"--entry ./{options.EntryPoint} ");
            result.Append($"--output-path {rootPath} ");
            result.Append($"--output-filename {options.OutputFileName} ");
            result.Append(string.Format(DevToolType, options.DevToolType.GetWebpackValue()));

            if (options.EnableHotLoading)
            {
                result.Append("--hot --inline ");
                result.Append($"--host {options.DevServerOptions.Host} ");
                result.Append($"--port {options.DevServerOptions.Port} ");
                result.Append($"--output-public-path http://{options.DevServerOptions.Host}:{options.DevServerOptions.Port}/ ");
            }

            return(result.ToString());
        }
Ejemplo n.º 5
0
        public WebPackMiddlewareOptions Execute(string configFile, WebpackOptions options)
        {
            var enableHotLoading = options.DevServerOptions != null;
            var toolToExecute    = enableHotLoading ? WEBPACK_DEV_SERVER : WEBPACK;
            var logger           = _loggerFactory.CreateLogger(toolToExecute);

            logger.LogInformation($"Verifying required tools are installed");
            EnsuereNodeModluesInstalled(enableHotLoading, logger);
            logger.LogInformation($"All node modules are properly installed");

            logger.LogInformation($"{toolToExecute} Execution started");
            var hotModuleReplcementTag = options.EnableHotModuleReplacement && enableHotLoading ? "--hot" : string.Empty;
            var arguments = $"--config {configFile} {hotModuleReplcementTag}";

            logger.LogInformation($"{toolToExecute} is called with these arguments: {arguments}");
            new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName        = GetWebpackToolToExeceute(toolToExecute),
                    Arguments       = arguments,
                    UseShellExecute = false
                }
            }.Start();
            logger.LogInformation($"{toolToExecute} started successfully");

            var middleWareOptions = new WebPackMiddlewareOptions
            {
                OutputFileNames  = options.GetBundlesList(),
                EnableHotLoading = enableHotLoading
            };

            if (!enableHotLoading)
            {
                return(middleWareOptions);
            }

            middleWareOptions.Host = options.DevServerOptions.Host;
            middleWareOptions.Port = options.DevServerOptions.Port;
            return(middleWareOptions);
        }
Ejemplo n.º 6
0
        public WebPackMiddlewareOptions Execute(WebpackOptions options)
        {
            var toolToExecute = options.EnableHotLoading ? WEBPACK_DEV_SERVER : WEBPACK;
            var logger        = _loggerFactory.CreateLogger(toolToExecute);

            logger.LogInformation($"Verifying required tools are installed");
            EnsuereNodeModluesInstalled(options.EnableHotLoading, logger);
            logger.LogInformation($"All node modules are properly installed");

            var includeDefaultConfigFile = CreateWebpackConfigurationFile(options);

            logger.LogInformation($"{toolToExecute} Execution started");
            try {
                var arguments = ArgumentsHelper.GetWebpackArguments(_webRootPath, options, includeDefaultConfigFile);
                logger.LogInformation($"{toolToExecute} is called with these arguments: {arguments}");
                new Process
                {
                    StartInfo = new ProcessStartInfo()
                    {
                        FileName        = GetWebpackToolToExeceute(toolToExecute),
                        Arguments       = arguments,
                        UseShellExecute = false
                    }
                }.Start();
                logger.LogInformation($"{toolToExecute} started successfully");

                return(new WebPackMiddlewareOptions {
                    EnableHotLoading = options.EnableHotLoading,
                    OutputFileNames = options.GetBundlesList(),
                    Host = options.DevServerOptions.Host,
                    Port = options.DevServerOptions.Port
                });
            }
            catch (Win32Exception) {
                throw new InvalidProgramException("IIS Express is not supported by Asp.net Webpack. Please use Kestrel instead");
            }
        }
Ejemplo n.º 7
0
		/// <summary>
		/// Adds webpack functionality to the application. It should be used only in development environment.
		/// This method does not require an external configuration file and covers the most usual cases for webpack.
		/// Based on the provided <paramref name="options"/> the underlying middleware will add the required script tags
		/// so there is not need to add them manually.
		/// </summary>
		public static IApplicationBuilder UseWebpack(this IApplicationBuilder app, WebpackOptions options) {
			var webpack = app.ApplicationServices.GetService<IWebpack>();
			var middleWareOptions = webpack.Execute(options);
			app.UseMiddleware<WebpackMiddleware>(middleWareOptions);
			return app;
		}
Ejemplo n.º 8
0
		private static void CreateWebpackConfigurationFile(WebpackOptions options) {
			if (!Directory.Exists("webpack")) {
				Directory.CreateDirectory("webpack");
			}
			var presets = new List<string>() {
				"es2015"
			};
			if (options.HandleJsxFiles) {
				presets.Add("react");
			}
			var query = new Query {
				Presets = presets
			};
			var loaders = new List<WebpackLoader>();
			loaders.Add(new WebpackLoader {
				Test = "/\\.js/",
				Loader = "babel-loader",
				Exclude = "/node_modules/",
				Query = query
			});
			if (options.HandleJsxFiles) {
				loaders.Add(new WebpackLoader {
					Test = "/\\.jsx/",
					Loader = "babel-loader",
					Exclude = "/node_modules/",
					Query = query
				});
			}
			var exports = new {
				module = new {
					loaders
				}
			};
			var jsonResult = JsonConvert.SerializeObject(exports,
				new JsonSerializerSettings {
					Formatting = Formatting.Indented,
					ContractResolver = new CamelCasePropertyNamesContractResolver()
				});
			var fileContent = $"module.exports = {jsonResult}";
			using (var fs = File.Create(Path.Combine("webpack", "webpack.dev.js"))) {
				using (var streamWriter = new StreamWriter(fs)) {
					streamWriter.WriteLine(fileContent);
				}
			}
		}
Ejemplo n.º 9
0
        private static bool CreateWebpackConfigurationFile(WebpackOptions options)
        {
            var presets = new List <string>()
            {
                "es2015"
            };

            if (options.HandleJsxFiles)
            {
                presets.Add("react");
            }
            var query = new Query {
                Presets = presets
            };
            var loaders = new List <WebpackLoader>();

            if (options.EnableES2015)
            {
                loaders.Add(new WebpackLoader {
                    Test    = "/\\.js/",
                    Loader  = "babel-loader",
                    Exclude = "/node_modules/",
                    Query   = query
                });
            }
            if (options.HandleJsxFiles)
            {
                loaders.Add(new WebpackLoader {
                    Test    = "/\\.jsx/",
                    Loader  = "babel-loader",
                    Exclude = "/node_modules/",
                    Query   = query
                });
            }
            var exports = new {
                module = new {
                    loaders
                }
            };

            // Create the external configuration file only if we need to use babel-loader
            if (loaders.Count > 0)
            {
                if (!Directory.Exists("webpack"))
                {
                    Directory.CreateDirectory("webpack");
                }
                var jsonResult = JsonConvert.SerializeObject(exports,
                                                             new JsonSerializerSettings {
                    Formatting       = Formatting.Indented,
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });
                var fileContent = $"module.exports = {jsonResult}";
                using (var fs = File.Create(Path.Combine("webpack", "webpack.dev.js"))) {
                    using (var streamWriter = new StreamWriter(fs)) {
                        streamWriter.WriteLine(fileContent);
                    }
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Adds webpack functionality to the application. It should be used only in development environment.
        /// This method requires an external configuration file and covers specific configurations based on an external config file.
        /// Based on the provided <paramref name="webpackOptions"/> the underlying middleware will add the required script tags
        /// so there is not need to add them manually.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="configFile">The path to the external configuration file e.g. webpack/webpack.development.js</param>
        /// <param name="webpackOptions">Configuration options which sets flags on the webpack command and adds the required script tags.</param>
        /// <returns></returns>
        public static IApplicationBuilder UseWebpack(this IApplicationBuilder app, string configFile, WebpackOptions webpackOptions)
        {
            var webpack = app.ApplicationServices.GetService <IWebpack>();
            var options = webpack.Execute(configFile, webpackOptions);

            app.UseMiddleware <WebpackMiddleware>(options);
            return(app);
        }