/// <summary> /// Loads a transformed JavaScript file from the disk cache. If the cache is invalid or there is /// no cached version, returns <c>null</c>. /// </summary> /// <param name="filename">Name of the file to load</param> /// /// <param name="hash">Hash of the input file, to validate the cache</param> /// <param name="forceGenerateSourceMap"> /// <c>true</c> to re-transform the file if a cached version with no source map is available /// </param> /// <returns></returns> protected virtual JavaScriptWithSourceMap LoadFromFileCache(string filename, string hash, bool forceGenerateSourceMap) { var cacheFilename = GetOutputPath(filename); if (!_fileSystem.FileExists(cacheFilename)) { // Cache file doesn't exist on disk return(null); } var cacheContents = _fileSystem.ReadAsString(cacheFilename); if (!_fileCacheHash.ValidateHash(cacheContents, hash)) { // Hash of the cache is invalid (file changed since the time the cache was written). return(null); } // Cache is valid :D // See if we have a source map cached alongside the file SourceMap sourceMap = null; var sourceMapFilename = GetSourceMapOutputPath(filename); if (_fileSystem.FileExists(sourceMapFilename)) { try { var sourceMapString = _fileSystem.ReadAsString(sourceMapFilename); if (!string.IsNullOrEmpty(sourceMapString)) { sourceMap = SourceMap.FromJson(sourceMapString); } } catch (Exception e) { // Just ignore it Trace.WriteLine("Error reading source map file: " + e.Message); } } // If forceGenerateSourceMap is true, we need to explicitly ignore this cached version // if there's no source map if (forceGenerateSourceMap && sourceMap == null) { return(null); } return(new JavaScriptWithSourceMap { Code = cacheContents, SourceMap = sourceMap, Hash = hash, }); }
/// <summary> /// Transforms a JSX file. Results of the JSX to JavaScript transformation are cached. /// </summary> /// <param name="filename">Name of the file to load</param> /// <param name="useHarmony"><c>true</c> if support for es6 syntax should be rewritten.</param> /// <returns>JavaScript</returns> public string TransformJsxFile(string filename, bool?useHarmony = null) { var fullPath = _fileSystem.MapPath(filename); // 1. Check in-memory cache return(_cache.GetOrInsert( key: string.Format(JSX_CACHE_KEY, filename), slidingExpiration: TimeSpan.FromMinutes(30), cacheDependencyFiles: new[] { fullPath }, getData: () => { // 2. Check on-disk cache var contents = _fileSystem.ReadAsString(filename); var hash = _fileCacheHash.CalculateHash(contents); var cacheFilename = GetJsxOutputPath(filename); if (_fileSystem.FileExists(cacheFilename)) { var cacheContents = _fileSystem.ReadAsString(cacheFilename); if (_fileCacheHash.ValidateHash(cacheContents, hash)) { // Cache is valid :D return cacheContents; } } // 3. Not cached, perform the transformation return TransformJsxWithHeader(contents, hash, useHarmony); } )); }