Merge pull request #23958 from dennispg/master

Updates for webpack 4.0
This commit is contained in:
Armando Aguirre
2018-03-05 15:27:39 -08:00
committed by GitHub
8 changed files with 2188 additions and 235 deletions

View File

@@ -52,17 +52,6 @@ configuration = {
]
};
configuration = {
// ...
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "commons",
filename: "commons.js",
}),
new ExtractTextPlugin("[name].css")
]
};
configuration = {
// ...
module: {

View File

@@ -1,4 +1,4 @@
// Type definitions for webpack 3.8
// Type definitions for webpack 4.0
// Project: https://github.com/webpack/webpack
// Definitions by: Qubo <https://github.com/tkqubo>
// Benjamin Lim <https://github.com/bumbleblym>
@@ -35,6 +35,8 @@ declare function webpack(options: webpack.Configuration[]): webpack.MultiCompile
declare namespace webpack {
interface Configuration {
/** Enable production optimizations or development hints. */
mode?: "development" | "production" | "none";
/** Name of the configuration. Used when loading multiple configurations. */
name?: string;
/**
@@ -105,6 +107,9 @@ declare namespace webpack {
performance?: Options.Performance;
/** Limit the number of parallel processed modules. Can be used to fine tune performance or to get more reliable profiling results */
parallelism?: number;
/** Optimization options */
optimization?: Options.Optimization;
}
interface Entry {
@@ -182,9 +187,13 @@ declare namespace webpack {
sourcePrefix?: string;
/** This option enables cross-origin loading of chunks. */
crossOriginLoading?: string | boolean;
/** Algorithm used for generation the hash (see node.js crypto package) */
hashFunction?: string | ((algorithm: string, options?: any) => any);
/** An expression which is used to address the global object/scope in runtime code. */
globalObject?: string;
}
interface BaseModule {
interface Module {
/** A array of applied pre loaders. */
preLoaders?: Rule[];
/** A array of applied post loaders. */
@@ -203,18 +212,10 @@ declare namespace webpack {
wrappedContextRecursive?: boolean;
wrappedContextCritical?: boolean;
strictExportPresence?: boolean;
}
interface OldModule extends BaseModule {
/** An array of automatically applied loaders. */
loaders: Rule[];
}
interface NewModule extends BaseModule {
/** An array of rules applied for modules. */
rules: Rule[];
}
type Module = OldModule | NewModule;
interface Resolve {
/**
* A list of directories to resolve modules from.
@@ -376,7 +377,10 @@ declare namespace webpack {
options?: { [name: string]: any };
}
type Loader = string | OldLoader | NewLoader;
interface ParserOptions {
[optName: string]: any;
system?: boolean;
}
/**
* There are direct and delegate rules. Direct Rules need a test, Delegate rules delegate to subrules bringing their own.
* Direct rules can optionally contain delegate keys (oneOf, rules).
@@ -416,11 +420,17 @@ declare namespace webpack {
* For each different parser options object a new parser is created and plugins can apply plugins depending on the parser options.
* Many of the default plugins apply their parser plugins only if a property in the parser options is not set or true.
*/
parser?: { [optName: string]: any };
parser?: ParserOptions;
/** An array of Rules that is also used when the Rule matches. */
rules?: Rule[];
/** An array of Rules from which only the first matching Rule is used when the Rule matches. */
oneOf?: Rule[];
/** Configures module resolving. */
resolve?: Resolve;
/** Configures the module type. */
type?: "javascript/auto" | "javascript/esm" | "javascript/dynamic" | "json" | "webassembly/experimental";
/** Flags a module as with or without side effects */
sideEffects?: boolean;
}
interface BaseDirectRule extends BaseRule {
/** A condition that must be met */
@@ -496,6 +506,97 @@ declare namespace webpack {
}
type Stats = Stats.ToStringOptions;
type WatchOptions = ICompiler.WatchOptions;
interface CacheGroupsOptions {
/** Assign modules to a cache group */
test?: ((...args: any[]) => boolean) | string | RegExp;
/** Select chunks for determining cache group content (defaults to \"initial\", \"initial\" and \"all\" requires adding these chunks to the HTML) */
chunks?: "initial" | "async" | "all";
/** Ignore minimum size, minimum chunks and maximum requests and always create chunks for this cache group */
enforce?: boolean;
/** Priority of this cache group */
priority?: number;
/** Minimal size for the created chunk */
minSize?: number;
/** Minimum number of times a module has to be duplicated until it's considered for splitting */
minChunks?: number;
/** Maximum number of requests which are accepted for on-demand loading */
maxAsyncRequests?: number;
/** Maximum number of initial chunks which are accepted for an entry point */
maxInitialRequests?: number;
/** Try to reuse existing chunk (with name) when it has matching modules */
reuseExistingChunk?: boolean;
/** Give chunks created a name (chunks with equal name are merged) */
name?: boolean | string | ((...args: any[]) => any);
}
interface SplitChunksOptions {
/** Select chunks for determining shared modules (defaults to \"async\", \"initial\" and \"all\" requires adding these chunks to the HTML) */
chunks?: "initial" | "async" | "all";
/** Minimal size for the created chunk */
minSize?: number;
/** Minimum number of times a module has to be duplicated until it's considered for splitting */
minChunks?: number;
/** Maximum number of requests which are accepted for on-demand loading */
maxAsyncRequests?: number;
/** Maximum number of initial chunks which are accepted for an entry point */
maxInitialRequests?: number;
/** Give chunks created a name (chunks with equal name are merged) */
name?: boolean | string | ((...args: any[]) => any);
/** Assign modules to a cache group (modules from different cache groups are tried to keep in separate chunks) */
cacheGroups?: false | string | ((...args: any[]) => any) | RegExp | CacheGroupsOptions;
}
interface RuntimeChunkOptions {
/** The name or name factory for the runtime chunks. */
name?: string | ((...args: any[]) => any);
}
interface Optimization {
/**
* Modules are removed from chunks when they are already available in all parent chunk groups.
* This reduces asset size. Smaller assets also result in faster builds since less code generation has to be performed.
*/
removeAvailableModules?: boolean;
/** Empty chunks are removed. This reduces load in filesystem and results in faster builds. */
removeEmptyChunks?: boolean;
/** Equal chunks are merged. This results in less code generation and faster builds. */
mergeDuplicateChunks?: boolean;
/** Chunks which are subsets of other chunks are determined and flagged in a way that subsets dont have to be loaded when the bigger chunk has been loaded. */
flagIncludedChunks?: boolean;
/** Give more often used ids smaller (shorter) values. */
occurrenceOrder?: boolean;
/** Determine exports for each module when possible. This information is used by other optimizations or code generation. I. e. to generate more efficient code for export * from. */
providedExports?: boolean;
/**
* Determine used exports for each module. This depends on optimization.providedExports. This information is used by other optimizations or code generation.
* I. e. exports are not generated for unused exports, export names are mangled to single char identifiers when all usages are compatible.
* DCE in minimizers will benefit from this and can remove unused exports.
*/
usedExports?: boolean;
/**
* Recognise the sideEffects flag in package.json or rules to eliminate modules. This depends on optimization.providedExports and optimization.usedExports.
* These dependencies have a cost, but eliminating modules has positive impact on performance because of less code generation. It depends on your codebase.
* Try it for possible performance wins.
*/
sideEffects?: boolean;
/** Tries to find segments of the module graph which can be safely concatenated into a single module. Depends on optimization.providedExports and optimization.usedExports. */
concatenateModules?: boolean;
/** Finds modules which are shared between chunk and splits them into separate chunks to reduce duplication or separate vendor modules from application modules. */
splitChunks?: SplitChunksOptions | false;
/** Create a separate chunk for the webpack runtime code and chunk hash maps. This chunk should be inlined into the HTML */
runtimeChunk?: boolean | "single" | "multiple" | RuntimeChunkOptions;
/** Avoid emitting assets when errors occur. */
noEmitOnErrors?: boolean;
/** Instead of numeric ids, give modules readable names for better debugging. */
namedModules?: boolean;
/** Instead of numeric ids, give chunks readable names for better debugging. */
namedChunks?: boolean;
/** Defines the process.env.NODE_ENV constant to a compile-time-constant value. This allows to remove development only code from code. */
nodeEnv?: string | false;
/** Use the minimizer (optimization.minimizer, by default uglify-js) to minimize output assets. */
minimize?: boolean;
/** Minimizer(s) to use for minimizing the output */
minimizer?: Array<Plugin | Tapable.Plugin>;
/** Generate records with relative paths to be able to move the context folder". */
portableRecords?: boolean;
}
}
// tslint:disable-next-line:interface-name
@@ -829,6 +930,7 @@ declare namespace webpack {
constructor(options: any);
}
/** @deprecated use config.optimization.namedModules */
class NamedModulesPlugin extends Plugin {
constructor();
}
@@ -837,15 +939,12 @@ declare namespace webpack {
constructor(nameResolver?: (chunk: any) => string | null);
}
/** @deprecated use config.optimization.noEmitOnErrors */
class NoEmitOnErrorsPlugin extends Plugin {
constructor();
}
/** @deprecated use webpack.NoEmitOnErrorsPlugin */
class NoErrorsPlugin extends Plugin {
constructor();
}
class NormalModuleReplacementPlugin extends Plugin {
constructor(resourceRegExp: any, newResource: any);
}
@@ -868,6 +967,10 @@ declare namespace webpack {
constructor(definitions: { [key: string]: any });
}
class SplitChunksPlugin extends Plugin {
constructor(options?: Options.SplitChunksOptions);
}
class SourceMapDevToolPlugin extends Plugin {
constructor(options?: null | false | string | SourceMapDevToolPlugin.Options);
}
@@ -899,6 +1002,7 @@ declare namespace webpack {
}
namespace optimize {
/** @deprecated use config.optimization.concatenateModules */
class ModuleConcatenationPlugin extends Plugin { }
class AggressiveMergingPlugin extends Plugin {
constructor(options?: AggressiveMergingPlugin.Options);
@@ -925,62 +1029,6 @@ declare namespace webpack {
}
}
class CommonsChunkPlugin extends Plugin {
constructor(options?: CommonsChunkPlugin.Options);
}
namespace CommonsChunkPlugin {
type MinChunksFn = (module: any, count: number) => boolean;
interface Options {
/**
* The chunk name of the commons chunk. An existing chunk can be selected by passing a name of an existing chunk.
* If an array of strings is passed this is equal to invoking the plugin multiple times for each chunk name.
* If omitted and `options.async` or `options.children` is set all chunks are used,
* otherwise `options.filename` is used as chunk name.
*/
name?: string;
names?: string[];
/**
* The filename template for the commons chunk. Can contain the same placeholders as `output.filename`.
* If omitted the original filename is not modified (usually `output.filename` or `output.chunkFilename`).
*/
filename?: string;
/**
* The minimum number of chunks which need to contain a module before it's moved into the commons chunk.
* The number must be greater than or equal 2 and lower than or equal to the number of chunks.
* Passing `Infinity` just creates the commons chunk, but moves no modules into it.
* By providing a `function` you can add custom logic. (Defaults to the number of chunks)
*/
minChunks?: number | MinChunksFn;
/**
* Select the source chunks by chunk names. The chunk must be a child of the commons chunk.
* If omitted all entry chunks are selected.
*/
chunks?: string[];
/**
* If `true` all children of the commons chunk are selected
*/
children?: boolean;
/**
* If `true` a new async commons chunk is created as child of `options.name` and sibling of `options.chunks`.
* It is loaded in parallel with `options.chunks`. It is possible to change the name of the output file
* by providing the desired string instead of `true`.
*/
async?: boolean | string;
/**
* Minimum size of all common module before a commons chunk is created.
*/
minSize?: number;
}
}
/** @deprecated */
class DedupePlugin extends Plugin {
constructor();
@@ -1197,11 +1245,6 @@ declare namespace webpack {
*/
inputValue: any;
/**
* The options passed to the Compiler.
*/
options: any;
/**
* A boolean flag. It is set when in debug mode.
*/
@@ -1256,6 +1299,9 @@ declare namespace webpack {
* Hacky access to the Module object being loaded.
*/
_module: any;
/** Flag if HMR is enabled */
hot: boolean;
}
}

1301
types/webpack/v3/index.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"source-map": "^0.6.0"
}
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"webpack": ["webpack/v3"]
}
},
"files": [
"index.d.ts",
"webpack-tests.ts"
]
}

View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -0,0 +1,667 @@
import webpack = require('webpack');
import { RawSourceMap } from 'source-map';
const {
optimize,
} = webpack;
let plugins: webpack.Plugin[];
/**
* Plugins
*/
/**
* optimize
*/
const {
AggressiveMergingPlugin,
} = optimize;
plugins = [
new AggressiveMergingPlugin(),
new AggressiveMergingPlugin({}),
new AggressiveMergingPlugin({
entryChunkMultiplicator: 10,
minSizeReduce: 1.5,
moveToParents: false,
}),
];
let configuration: webpack.Configuration;
let rule: webpack.Rule;
let plugin: webpack.Plugin;
declare const __dirname: string;
//
// https://webpack.github.io/docs/using-loaders.html
//
configuration = {
module: {
loaders: [
{ test: /\.jade$/, loader: "jade" },
// => "jade" loader is used for ".jade" files
{ test: /\.css$/, loader: "style!css" },
// => "style" and "css" loader is used for ".css" files
// Alternative syntax:
{ test: /\.css$/, loaders: ["style", "css"] },
]
}
};
rule = { test: /\.png$/, loader: "url-loader?mimetype=image/png" };
rule = {
test: /\.png$/,
loader: "url-loader",
query: { mimetype: "image/png" }
};
//
// http://webpack.github.io/docs/tutorials/getting-started/
//
configuration = {
entry: "./entry.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
}
};
//
// https://webpack.js.org/configuration/entry-context/#dynamic-entry
//
configuration = {
entry: () => './demo'
};
configuration = {
entry: () => ['./demo', './demo2']
};
configuration = {
entry: () => new Promise((resolve) => resolve('./demo'))
};
configuration = {
entry: () => new Promise((resolve) => resolve(['./demo', './demo2']))
};
//
// https://webpack.github.io/docs/code-splitting.html
//
configuration = {
entry: {
app: "./app.js",
vendor: ["jquery", "underscore"],
},
output: {
filename: "bundle.js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
filename: "vendor.bundle.js",
}),
]
};
configuration = {
entry: { a: "./a", b: "./b" },
output: { filename: "[name].js" },
plugins: [new webpack.optimize.CommonsChunkPlugin({ name: "init.js" })]
};
//
// https://webpack.github.io/docs/stylesheets.html
//
configuration = {
// ...
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
}
};
//
// https://webpack.github.io/docs/optimization.html
//
configuration = {
entry: {
p1: "./page1",
p2: "./page2",
p3: "./page3"
},
output: {
filename: "[name].entry.chunk.js"
}
};
const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
configuration = {
entry: {
p1: "./page1",
p2: "./page2",
p3: "./page3"
},
output: {
filename: "[name].entry.chunk.js"
},
plugins: [
new CommonsChunkPlugin({ name: "commons.chunk.js" })
]
};
configuration = {
entry: {
p1: "./page1",
p2: "./page2",
p3: "./page3",
ap1: "./admin/page1",
ap2: "./admin/page2"
},
output: {
filename: "[name].js"
},
};
// <script>s required:
// page1.html: commons.js, p1.js
// page2.html: commons.js, p2.js
// page3.html: p3.js
// admin-page1.html: commons.js, admin-commons.js, ap1.js
// admin-page2.html: commons.js, admin-commons.js, ap2.js
configuration = {
entry: {
p1: "./page1",
p2: "./page2",
commons: "./entry-for-the-commons-chunk"
},
plugins: [
new CommonsChunkPlugin({
name: "commons",
filename: "commons.js",
}),
]
};
//
// https://webpack.github.io/docs/long-term-caching.html
//
configuration = {
output: {
path: path.join(__dirname, "assets", "[hash]"),
publicPath: "assets/[hash]/",
filename: "output.[hash].bundle.js",
chunkFilename: "[id].[hash].bundle.js"
}
};
configuration = { output: { chunkFilename: "[chunkhash].bundle.js" } };
//
// https://webpack.github.io/docs/configuration.html
//
configuration = {
entry: [
"./entry1",
"./entry2"
]
};
configuration = {
devtool: "inline-source-map"
};
configuration = {
devtool: false
};
configuration = {
resolve: {
modules: [__dirname]
}
};
rule = {
test: /\.jsx$/,
include: [
path.resolve(__dirname, "app/src"),
path.resolve(__dirname, "app/test")
],
exclude: [
path.resolve(__dirname, "node_modules")
],
loader: "babel-loader"
};
declare const require: any;
declare const path: any;
configuration = {
plugins: [
function(this: webpack.Compiler) {
this.plugin("done", stats => {
require("fs").writeFileSync(
path.join(__dirname, "...", "stats.json"),
JSON.stringify(stats.toJson()));
});
}
]
};
//
// https://webpack.github.io/docs/list-of-plugins.html
//
declare const resourceRegExp: any;
declare const newResource: any;
declare const contextRegExp: any;
declare const newContentResource: any;
declare const newContentRecursive: any;
declare const newContentRegExp: any;
declare const requestRegExp: any;
declare const options: any;
declare const definitions: any;
declare const paths: any;
const preferEntry = true;
declare const context: any;
declare const request: any;
declare const types: any;
declare const banner: any;
plugin = new webpack.NormalModuleReplacementPlugin(resourceRegExp, newResource);
plugin = new webpack.ContextReplacementPlugin(
resourceRegExp,
newContentResource,
newContentRecursive,
newContentRegExp);
plugin = new webpack.ContextReplacementPlugin(
resourceRegExp,
newContentResource,
newContentRecursive);
plugin = new webpack.ContextReplacementPlugin(
resourceRegExp,
newContentResource);
plugin = new webpack.ContextReplacementPlugin(resourceRegExp);
plugin = new webpack.DllPlugin({
context: 'dir-context',
name: 'dll-name',
path: 'manifest-path'
});
plugin = new webpack.DllPlugin([{
context: 'dir-context',
name: 'dll-name',
path: 'manifest-path'
}]);
plugin = new webpack.DllReferencePlugin({
content: 'dll content',
context: 'dir-context',
manifest: {
content: 'dll content',
name: 'dll name'
},
name: 'dll name',
scope: 'dll prefix',
sourceType: 'var'
});
plugin = new webpack.IgnorePlugin(requestRegExp);
plugin = new webpack.IgnorePlugin(requestRegExp, contextRegExp);
plugin = new webpack.PrefetchPlugin(context, request);
plugin = new webpack.PrefetchPlugin(request);
plugin = new webpack.BannerPlugin('banner');
plugin = new webpack.BannerPlugin({
banner: 'banner'
});
plugin = new webpack.BannerPlugin({
banner: 'banner',
entryOnly: true,
exclude: /index/,
include: 'test',
raw: false,
test: ['test', /index/]
});
plugin = new webpack.optimize.DedupePlugin();
plugin = new webpack.optimize.LimitChunkCountPlugin(options);
plugin = new webpack.optimize.MinChunkSizePlugin(options);
plugin = new webpack.optimize.OccurrenceOrderPlugin(preferEntry);
plugin = new webpack.optimize.OccurrenceOrderPlugin(preferEntry);
plugin = new webpack.optimize.UglifyJsPlugin(options);
plugin = new webpack.optimize.UglifyJsPlugin();
plugin = new webpack.optimize.UglifyJsPlugin({
parallel: true
});
plugin = new webpack.optimize.UglifyJsPlugin({
parallel: {
cache: true,
workers: 2
}
});
plugin = new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
});
plugin = new webpack.optimize.UglifyJsPlugin({
sourceMap: false,
comments: true,
beautify: true,
test: 'foo',
exclude: /node_modules/,
include: 'test'
});
plugin = new webpack.optimize.UglifyJsPlugin({
mangle: {
except: ['$super', '$', 'exports', 'require']
}
});
plugin = new webpack.optimize.UglifyJsPlugin({
comments: (astNode: any, comment: any) => false
});
plugin = new webpack.optimize.CommonsChunkPlugin(options);
plugin = new CommonsChunkPlugin({
name: "commons",
// (the commons chunk name)
filename: "commons.js",
// (the filename of the commons chunk)
// minChunks: 3,
// (Modules must be shared between 3 entries)
// chunks: ["pageA", "pageB"],
// (Only use these entries)
});
plugin = new CommonsChunkPlugin({
// names: ["app", "subPageA"]
// (choose the chunks, or omit for all chunks)
children: true,
// (select all children of chosen chunks)
// minChunks: 3,
// (3 children must share the module before it's moved)
});
plugin = new CommonsChunkPlugin({
// names: ["app", "subPageA"]
// (choose the chunks, or omit for all chunks)
children: true,
// (use all children of the chunk)
async: true,
// (create an async commons chunk)
// minChunks: 3,
// (3 children must share the module before it's separated)
});
plugin = new webpack.DefinePlugin(definitions);
plugin = new webpack.DefinePlugin({
VERSION: JSON.stringify("5fa3b9"),
BROWSER_SUPPORTS_HTML5: true,
TWO: "1+1",
"typeof window": JSON.stringify("object")
});
plugin = new webpack.ProvidePlugin(definitions);
plugin = new webpack.ProvidePlugin({
$: "jquery"
});
plugin = new webpack.SourceMapDevToolPlugin({
//// asset matching
test: /\.js$/,
// include: Condition | Condition[],
exclude: [
/node_modules/
],
//
//// file and reference
filename: null, // | string
// append: false | string,
//// sources naming
// moduleFilenameTemplate: string,
// fallbackModuleFilenameTemplate: string,
//
//// quality/performance
module: true,
columns: true,
lineToLine: false // | { test?: Condition | Condition[], ... }
});
plugin = new webpack.EvalSourceMapDevToolPlugin(false);
plugin = new webpack.HotModuleReplacementPlugin();
plugin = new webpack.ExtendedAPIPlugin();
plugin = new webpack.NoErrorsPlugin();
plugin = new webpack.NoEmitOnErrorsPlugin();
plugin = new webpack.WatchIgnorePlugin(paths);
plugin = new webpack.LoaderOptionsPlugin({
debug: true
});
plugin = new webpack.EnvironmentPlugin(['a', 'b']);
plugin = new webpack.EnvironmentPlugin({ a: true, b: 'c' });
plugin = new webpack.ProgressPlugin((percent: number, message: string) => { });
plugin = new webpack.ProgressPlugin((percent: number, message: string, moduleProgress?: string, activeModules?: string, moduleName?: string) => { });
plugin = new webpack.HashedModuleIdsPlugin();
plugin = new webpack.HashedModuleIdsPlugin({
hashFunction: 'sha256',
hashDigest: 'hex',
hashDigestLength: 20
});
//
// http://webpack.github.io/docs/node.js-api.html
//
// returns a Compiler instance
webpack({
// configuration
}, (err, stats) => {
// ...
});
// returns a Compiler instance
let compiler = webpack({
// configuration
});
compiler.run((err, stats) => {
// ...
});
// or
compiler.watch({ // watch options:
aggregateTimeout: 300, // wait so long for more changes
poll: true // use polling instead of native watchers
// pass a number to set the polling interval
}, (err, stats) => {
// ...
});
// or
compiler.watch({ // watch options:
ignored: 'foo/**/*'
}, (err, stats) => {
// ...
});
// or
compiler.watch({ // watch options:
ignored: /node_modules/
}, (err, stats) => {
// ...
});
declare function handleFatalError(err: Error): void;
declare function handleSoftErrors(errs: string[]): void;
declare function handleWarnings(errs: string[]): void;
declare function successfullyCompiled(): void;
webpack({
// configuration
}, (err, stats) => {
if (err) {
handleFatalError(err);
return;
}
const jsonStats = stats.toJson();
const jsonStatsWithAllOptions = stats.toJson({
assets: true,
assetsSort: "field",
cached: true,
children: true,
chunks: true,
chunkModules: true,
chunkOrigins: true,
chunksSort: "field",
context: "../src/",
errors: true,
errorDetails: true,
hash: true,
modules: true,
modulesSort: "field",
publicPath: true,
reasons: true,
source: true,
timings: true,
version: true,
warnings: true,
warningsFilter: ["filter", /filter/],
excludeAssets: ["filter", "excluded"]
});
if (jsonStats.errors.length > 0) {
handleSoftErrors(jsonStats.errors);
return;
}
if (jsonStats.warnings.length > 0) {
handleWarnings(jsonStats.warnings);
}
successfullyCompiled();
});
declare const fs: any;
compiler = webpack({});
compiler.outputFileSystem = fs;
compiler.run((err, stats) => {
// ...
const fileContent = fs.readFileSync("...");
});
//
// https://github.com/webpack/webpack/blob/master/test/configCases/rule-set/simple/webpack.config.js
//
rule = {
test: {
or: [
require.resolve("./a"),
require.resolve("./c"),
]
},
loader: "./loader",
options: "third"
};
configuration = {
module: {
rules: [
{
oneOf: [
{
test: {
and: [
/a.\.js$/,
/b\.js$/
]
},
loader: "./loader?first"
},
{
test: [
require.resolve("./a"),
require.resolve("./c"),
],
issuer: require.resolve("./b"),
use: [
"./loader?second-1",
{
loader: "./loader",
options: "second-2"
},
{
loader: "./loader",
options: {
get: () => "second-3"
}
}
]
},
{
test: {
or: [
require.resolve("./a"),
require.resolve("./c"),
]
},
loader: "./loader",
options: "third"
}
]
}
]
}
};
class TestResolvePlugin implements webpack.ResolvePlugin {
apply(resolver: any) {
resolver.plugin('before-existing-directory', (request: any, callback: any) => {
callback();
});
}
}
const performance: webpack.Options.Performance = {
hints: 'error',
maxEntrypointSize: 400000,
maxAssetSize: 100000,
assetFilter: assetFilename => assetFilename.endsWith('.js'),
};
configuration = {
performance,
};
function loader(this: webpack.loader.LoaderContext, source: string | Buffer, sourcemap?: RawSourceMap): void {
this.cacheable();
this.async();
this.addDependency('');
this.resolve('context', 'request', (err: Error, result: string) => { });
this.emitWarning('warning message');
this.emitWarning(new Error('warning message'));
this.emitError('error message');
this.emitError(new Error('error message'));
this.callback(null, source);
}
(loader as webpack.loader.Loader).raw = true;
(loader as webpack.loader.Loader).pitch = (remainingRequest: string, precedingRequest: string, data: any) => { };
const loaderRef: webpack.loader.Loader = loader;
console.log(loaderRef.raw === true);

View File

@@ -34,24 +34,6 @@ let rule: webpack.Rule;
let plugin: webpack.Plugin;
declare const __dirname: string;
//
// https://webpack.github.io/docs/using-loaders.html
//
configuration = {
module: {
loaders: [
{ test: /\.jade$/, loader: "jade" },
// => "jade" loader is used for ".jade" files
{ test: /\.css$/, loader: "style!css" },
// => "style" and "css" loader is used for ".css" files
// Alternative syntax:
{ test: /\.css$/, loaders: ["style", "css"] },
]
}
};
rule = { test: /\.png$/, loader: "url-loader?mimetype=image/png" };
rule = {
@@ -60,23 +42,6 @@ rule = {
query: { mimetype: "image/png" }
};
//
// http://webpack.github.io/docs/tutorials/getting-started/
//
configuration = {
entry: "./entry.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
}
};
//
// https://webpack.js.org/configuration/entry-context/#dynamic-entry
//
@@ -97,45 +62,6 @@ configuration = {
entry: () => new Promise((resolve) => resolve(['./demo', './demo2']))
};
//
// https://webpack.github.io/docs/code-splitting.html
//
configuration = {
entry: {
app: "./app.js",
vendor: ["jquery", "underscore"],
},
output: {
filename: "bundle.js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
filename: "vendor.bundle.js",
}),
]
};
configuration = {
entry: { a: "./a", b: "./b" },
output: { filename: "[name].js" },
plugins: [new webpack.optimize.CommonsChunkPlugin({ name: "init.js" })]
};
//
// https://webpack.github.io/docs/stylesheets.html
//
configuration = {
// ...
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
}
};
//
// https://webpack.github.io/docs/optimization.html
//
@@ -151,21 +77,6 @@ configuration = {
}
};
const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
configuration = {
entry: {
p1: "./page1",
p2: "./page2",
p3: "./page3"
},
output: {
filename: "[name].entry.chunk.js"
},
plugins: [
new CommonsChunkPlugin({ name: "commons.chunk.js" })
]
};
configuration = {
entry: {
p1: "./page1",
@@ -178,26 +89,6 @@ configuration = {
filename: "[name].js"
},
};
// <script>s required:
// page1.html: commons.js, p1.js
// page2.html: commons.js, p2.js
// page3.html: p3.js
// admin-page1.html: commons.js, admin-commons.js, ap1.js
// admin-page2.html: commons.js, admin-commons.js, ap2.js
configuration = {
entry: {
p1: "./page1",
p2: "./page2",
commons: "./entry-for-the-commons-chunk"
},
plugins: [
new CommonsChunkPlugin({
name: "commons",
filename: "commons.js",
}),
]
};
//
// https://webpack.github.io/docs/long-term-caching.html
@@ -374,43 +265,6 @@ plugin = new webpack.optimize.UglifyJsPlugin({
plugin = new webpack.optimize.UglifyJsPlugin({
comments: (astNode: any, comment: any) => false
});
plugin = new webpack.optimize.CommonsChunkPlugin(options);
plugin = new CommonsChunkPlugin({
name: "commons",
// (the commons chunk name)
filename: "commons.js",
// (the filename of the commons chunk)
// minChunks: 3,
// (Modules must be shared between 3 entries)
// chunks: ["pageA", "pageB"],
// (Only use these entries)
});
plugin = new CommonsChunkPlugin({
// names: ["app", "subPageA"]
// (choose the chunks, or omit for all chunks)
children: true,
// (select all children of chosen chunks)
// minChunks: 3,
// (3 children must share the module before it's moved)
});
plugin = new CommonsChunkPlugin({
// names: ["app", "subPageA"]
// (choose the chunks, or omit for all chunks)
children: true,
// (use all children of the chunk)
async: true,
// (create an async commons chunk)
// minChunks: 3,
// (3 children must share the module before it's separated)
});
plugin = new webpack.DefinePlugin(definitions);
plugin = new webpack.DefinePlugin({
VERSION: JSON.stringify("5fa3b9"),
@@ -445,7 +299,6 @@ plugin = new webpack.SourceMapDevToolPlugin({
plugin = new webpack.EvalSourceMapDevToolPlugin(false);
plugin = new webpack.HotModuleReplacementPlugin();
plugin = new webpack.ExtendedAPIPlugin();
plugin = new webpack.NoErrorsPlugin();
plugin = new webpack.NoEmitOnErrorsPlugin();
plugin = new webpack.WatchIgnorePlugin(paths);
plugin = new webpack.LoaderOptionsPlugin({
@@ -665,3 +518,65 @@ function loader(this: webpack.loader.LoaderContext, source: string | Buffer, sou
(loader as webpack.loader.Loader).pitch = (remainingRequest: string, precedingRequest: string, data: any) => { };
const loaderRef: webpack.loader.Loader = loader;
console.log(loaderRef.raw === true);
/**
* New v4 tests
*/
configuration = {
};
configuration = {
mode: "development"
};
configuration = {
mode: "production"
};
configuration = {
mode: "development",
optimization: {
removeAvailableModules: true,
removeEmptyChunks: true,
mergeDuplicateChunks: true,
flagIncludedChunks: false,
occurrenceOrder: false,
providedExports: true,
usedExports: false,
sideEffects: false,
concatenateModules: false,
splitChunks: false,
runtimeChunk: true,
noEmitOnErrors: false,
namedModules: true,
namedChunks: true,
nodeEnv: "development",
minimize: false,
portableRecords: false
}
};
configuration = {
mode: "production",
optimization: {
removeAvailableModules: true,
removeEmptyChunks: true,
mergeDuplicateChunks: true,
flagIncludedChunks: true,
occurrenceOrder: true,
providedExports: true,
usedExports: true,
sideEffects: true,
concatenateModules: true,
splitChunks: { chunks: "async", minChunks: 2 },
runtimeChunk: true,
noEmitOnErrors: true,
namedModules: false,
namedChunks: false,
nodeEnv: "production",
minimize: true,
portableRecords: true
}
};
plugin = new webpack.SplitChunksPlugin({ chunks: "async", minChunks: 2 });