EntryOptionPlugin插件在项目中的路径webpack-2.2.0/lib/EntryOptionPlugin.js。
"use strict";
const SingleEntryPlugin = require("./SingleEntryPlugin");
const MultiEntryPlugin = require("./MultiEntryPlugin");
const DynamicEntryPlugin = require("./DynamicEntryPlugin");
module.exports = class EntryOptionPlugin {
apply(compiler) {
compiler.plugin("entry-option", (context, entry) => {
function itemToPlugin(item, name) {
if(Array.isArray(item)) {
return new MultiEntryPlugin(context, item, name);
} else {
return new SingleEntryPlugin(context, item, name);
}
}
if(typeof entry === "string" || Array.isArray(entry)) {
compiler.apply(itemToPlugin(entry, "main"));
} else if(typeof entry === "object") {
Object.keys(entry).forEach(name => compiler.apply(itemToPlugin(entry[name], name)));
} else if(typeof entry === "function") {
compiler.apply(new DynamicEntryPlugin(context, entry));
}
return true;
});
}
};
注册EntryOptionPlugin插件,触发entry-option钩子。
var EntryOptionPlugin = require("./EntryOptionPlugin");
compiler.apply(new EntryOptionPlugin()); // 注册EntryOptionPlugin插件
compiler.applyPluginsBailResult("entry-option", options.context, options.entry); // 触发entry-option钩子
1.字符串
module.exports = {
entry: './src/main.js', // 字符串
...
}
//等同于下面写法
module.exports = {
entry: {
main: './src/main.js',
}
...
}
2.数组 将多个资源预先合并,将数组中的最后一个元素作为实际的入口。使用string和数组定义入口时,chunk name默认为main。
module.exports = {
entry: ['./src/index.js','./src/main.js'], // 数组
...
}
3.对象 配置多入口文件,每一个入口分别生成一个chunk文件,chunk名称是object键值对的键的名称。
module.exports = {
entry: { // 分离第三方库
app: './src/app.js',
vendors: ['react','react-dom','react-router'],
},
output: {
filename: '[name].[contenthash].js',
path: __dirname + '/dist'
}
...
}
module.exports = {
entry: { // 多页面
pageOne: './src/pageOne/index.js',
pageTwo: './src/pageTwo/index.js',
pageThree: './src/pageThree/index.js'
},
output: {
filename: '[name].[contenthash].js',
path: __dirname + '/dist'
}
...
}
4.函数 通过函数动态配置返回entry。
module.exports = {
entry: function() {
let a = 'src/pages/a';
let b = 'src/pages/b';
return {
a: a,
b: b
}
}
output: {
filename: '[name].[contenthash].js',
path: __dirname + '/dist'
}
...
}