|
| 1 | +// When you're using Webpack, it's often convenient to be able to require modules from regular JavaScript |
| 2 | +// and have them transformed by Webpack. This is especially useful when doing ASP.NET server-side prerendering, |
| 3 | +// because it means your boot module can use whatever source language you like (e.g., TypeScript), and means |
| 4 | +// that your loader plugins (e.g., require('./mystyles.less')) work in exactly the same way on the server as |
| 5 | +// on the client. |
| 6 | +import 'es6-promise'; |
| 7 | +import ExternalsPlugin from 'webpack-externals-plugin'; |
| 8 | +import requireFromString from 'require-from-string'; |
| 9 | +import MemoryFS from 'memory-fs'; |
| 10 | +import * as webpack from 'webpack'; |
| 11 | +import { deepClone } from './DeepClone'; |
| 12 | + |
| 13 | +// Ensure we only go through the compile process once per [config, module] pair |
| 14 | +const loadViaWebpackPromisesCache: { [key: string]: any } = {}; |
| 15 | + |
| 16 | +export interface LoadViaWebpackCallback<T> { |
| 17 | + (error: any, result: T): void; |
| 18 | +} |
| 19 | + |
| 20 | +export function loadViaWebpack<T>(webpackConfigPath: string, modulePath: string, callback: LoadViaWebpackCallback<T>) { |
| 21 | + const cacheKey = JSON.stringify(webpackConfigPath) + JSON.stringify(modulePath); |
| 22 | + if (!(cacheKey in loadViaWebpackPromisesCache)) { |
| 23 | + loadViaWebpackPromisesCache[cacheKey] = loadViaWebpackNoCache(webpackConfigPath, modulePath); |
| 24 | + } |
| 25 | + loadViaWebpackPromisesCache[cacheKey].then(result => { |
| 26 | + callback(null, result); |
| 27 | + }, error => { |
| 28 | + callback(error, null); |
| 29 | + }) |
| 30 | +} |
| 31 | + |
| 32 | +function loadViaWebpackNoCache<T>(webpackConfigPath: string, modulePath: string) { |
| 33 | + return new Promise<T>((resolve, reject) => { |
| 34 | + // Load the Webpack config and make alterations needed for loading the output into Node |
| 35 | + const webpackConfig: webpack.Configuration = deepClone(require(webpackConfigPath)); |
| 36 | + webpackConfig.entry = modulePath; |
| 37 | + webpackConfig.target = 'node'; |
| 38 | + webpackConfig.output = { path: '/', filename: 'webpack-output.js', libraryTarget: 'commonjs' }; |
| 39 | + |
| 40 | + // In Node, we want anything under /node_modules/ to be loaded natively and not bundled into the output |
| 41 | + // (partly because it's faster, but also because otherwise there'd be different instances of modules |
| 42 | + // depending on how they were loaded, which could lead to errors) |
| 43 | + webpackConfig.plugins = webpackConfig.plugins || []; |
| 44 | + webpackConfig.plugins.push(new ExternalsPlugin({ type: 'commonjs', include: /node_modules/ })); |
| 45 | + |
| 46 | + // The CommonsChunkPlugin is not compatible with a CommonJS environment like Node, nor is it needed in that case |
| 47 | + webpackConfig.plugins = webpackConfig.plugins.filter(plugin => { |
| 48 | + return !(plugin instanceof webpack.optimize.CommonsChunkPlugin); |
| 49 | + }); |
| 50 | + |
| 51 | + // The typical use case for DllReferencePlugin is for referencing vendor modules. In a Node |
| 52 | + // environment, it doesn't make sense to load them from a DLL bundle, nor would that even |
| 53 | + // work, because then you'd get different module instances depending on whether a module |
| 54 | + // was referenced via a normal CommonJS 'require' or via Webpack. So just remove any |
| 55 | + // DllReferencePlugin from the config. |
| 56 | + // If someone wanted to load their own DLL modules (not an NPM module) via DllReferencePlugin, |
| 57 | + // that scenario is not supported today. We would have to add some extra option to the |
| 58 | + // asp-prerender tag helper to let you specify a list of DLL bundles that should be evaluated |
| 59 | + // in this context. But even then you'd need special DLL builds for the Node environment so that |
| 60 | + // external dependencies were fetched via CommonJS requires, so it's unclear how that could work. |
| 61 | + // The ultimate escape hatch here is just prebuilding your code as part of the application build |
| 62 | + // and *not* using asp-prerender-webpack-config at all, then you can do anything you want. |
| 63 | + webpackConfig.plugins = webpackConfig.plugins.filter(plugin => { |
| 64 | + // DllReferencePlugin is missing from webpack.d.ts for some reason, hence referencing it |
| 65 | + // as a key-value object property |
| 66 | + return !(plugin instanceof webpack['DllReferencePlugin']); |
| 67 | + }); |
| 68 | + |
| 69 | + // Create a compiler instance that stores its output in memory, then load its output |
| 70 | + const compiler = webpack(webpackConfig); |
| 71 | + compiler.outputFileSystem = new MemoryFS(); |
| 72 | + compiler.run((err, stats) => { |
| 73 | + if (err) { |
| 74 | + reject(err); |
| 75 | + } else { |
| 76 | + const fileContent = compiler.outputFileSystem.readFileSync('/webpack-output.js', 'utf8'); |
| 77 | + const moduleInstance = requireFromString<T>(fileContent); |
| 78 | + resolve(moduleInstance); |
| 79 | + } |
| 80 | + }); |
| 81 | + }); |
| 82 | +} |
0 commit comments