Skip to content

Commit 2747aad

Browse files
Add aspnet-webpack NPM package
1 parent b519e58 commit 2747aad

14 files changed

Lines changed: 290 additions & 0 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/typings/
2+
/node_modules/
3+
/*.js
4+
/*.d.ts
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
!/*.js
2+
!/*.d.ts
3+
/typings/
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
Copyright (c) .NET Foundation. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4+
these files except in compliance with the License. You may obtain a copy of the
5+
License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software distributed
10+
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
11+
CONDITIONS OF ANY KIND, either express or implied. See the License for the
12+
specific language governing permissions and limitations under the License.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Not for general use
2+
3+
This NPM package is an internal implementation detail of the `Microsoft.AspNet.SpaServices` NuGet package.
4+
5+
You should not use this package directly in your own applications, because it is not supported, and there are no
6+
guarantees about how its APIs will change in the future.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"name": "aspnet-webpack",
3+
"version": "1.0.0",
4+
"description": "Helpers for using Webpack in ASP.NET projects. Works in conjunction with the Microsoft.AspNet.SpaServices NuGet package.",
5+
"main": "index.js",
6+
"scripts": {
7+
"prepublish": "tsd update && tsc && echo 'Finished building NPM package \"aspnet-webpack\"'",
8+
"test": "echo \"Error: no test specified\" && exit 1"
9+
},
10+
"author": "Microsoft",
11+
"license": "Apache-2.0",
12+
"dependencies": {
13+
"es6-promise": "^3.1.2",
14+
"express": "^4.13.4",
15+
"memory-fs": "^0.3.0",
16+
"require-from-string": "^1.1.0",
17+
"webpack": "^1.12.14",
18+
"webpack-dev-middleware": "^1.5.1",
19+
"webpack-externals-plugin": "^1.0.0"
20+
}
21+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export function deepClone<T>(serializableObject: T): T {
2+
return JSON.parse(JSON.stringify(serializableObject));
3+
}
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
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+
}
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import * as express from 'express';
2+
import * as webpack from 'webpack';
3+
import { deepClone } from './DeepClone';
4+
5+
export interface CreateDevServerCallback {
6+
(error: any, result: { Port: number, PublicPath: string }): void;
7+
}
8+
9+
// These are the options passed by WebpackDevMiddleware.cs
10+
interface CreateDevServerOptions {
11+
webpackConfigPath: string;
12+
suppliedOptions: DevServerOptions;
13+
}
14+
15+
// These are the options configured in C# and then JSON-serialized, hence the C#-style naming
16+
interface DevServerOptions {
17+
HotModuleReplacement: boolean;
18+
ReactHotModuleReplacement: boolean;
19+
}
20+
21+
export function createWebpackDevServer(callback: CreateDevServerCallback, optionsJson: string) {
22+
const options: CreateDevServerOptions = JSON.parse(optionsJson);
23+
const webpackConfig: webpack.Configuration = deepClone(require(options.webpackConfigPath));
24+
const publicPath = (webpackConfig.output.publicPath || '').trim();
25+
if (!publicPath) {
26+
callback('To use the Webpack dev server, you must specify a value for \'publicPath\' on the \'output\' section of your webpack.config.', null);
27+
return;
28+
}
29+
30+
const enableHotModuleReplacement = options.suppliedOptions.HotModuleReplacement;
31+
const enableReactHotModuleReplacement = options.suppliedOptions.ReactHotModuleReplacement;
32+
if (enableReactHotModuleReplacement && !enableHotModuleReplacement) {
33+
callback('To use ReactHotModuleReplacement, you must also enable the HotModuleReplacement option.', null);
34+
return;
35+
}
36+
37+
const app = express();
38+
const defaultPort = 0; // 0 means 'choose randomly'. Could allow an explicit value to be supplied instead.
39+
const listener = app.listen(defaultPort, () => {
40+
// Build the final Webpack config based on supplied options
41+
if (enableHotModuleReplacement) {
42+
// TODO: Stop assuming there's an entry point called 'main'
43+
webpackConfig.entry['main'].unshift('webpack-hot-middleware/client');
44+
webpackConfig.plugins.push(
45+
new webpack.HotModuleReplacementPlugin()
46+
);
47+
48+
// Set up React HMR support if requested. This requires the 'aspnet-webpack-react' package.
49+
if (enableReactHotModuleReplacement) {
50+
let aspNetWebpackReactModule: any;
51+
try {
52+
aspNetWebpackReactModule = require('aspnet-webpack-react');
53+
} catch(ex) {
54+
callback('To use ReactHotModuleReplacement, you must install the NPM package \'aspnet-webpack-react\'.', null);
55+
return;
56+
}
57+
58+
aspNetWebpackReactModule.addReactHotModuleReplacementBabelTransform(webpackConfig);
59+
}
60+
}
61+
62+
// Attach Webpack dev middleware and optional 'hot' middleware
63+
const compiler = webpack(webpackConfig);
64+
app.use(require('webpack-dev-middleware')(compiler, {
65+
noInfo: true,
66+
publicPath: publicPath
67+
}));
68+
69+
if (enableHotModuleReplacement) {
70+
let webpackHotMiddlewareModule;
71+
try {
72+
webpackHotMiddlewareModule = require('webpack-hot-middleware');
73+
} catch (ex) {
74+
callback('To use HotModuleReplacement, you must install the NPM package \'webpack-hot-middleware\'.', null);
75+
return;
76+
}
77+
app.use(webpackHotMiddlewareModule(compiler));
78+
}
79+
80+
// Tell the ASP.NET app what addresses we're listening on, so that it can proxy requests here
81+
callback(null, {
82+
Port: listener.address().port,
83+
PublicPath: removeTrailingSlash(publicPath)
84+
});
85+
});
86+
}
87+
88+
function removeTrailingSlash(str: string) {
89+
if (str.lastIndexOf('/') === str.length - 1) {
90+
str = str.substring(0, str.length - 1);
91+
}
92+
93+
return str;
94+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export { createWebpackDevServer } from './WebpackDevMiddleware';
2+
export { loadViaWebpack } from './LoadViaWebpack';
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
declare module 'memory-fs' {
2+
export default class MemoryFS {}
3+
}

0 commit comments

Comments
 (0)