原文地址:https://webpack.js.org/concepts/entry-points/
翻译:xiyoki
Entry Points
就如简介中提到的一样,在webpack配置文件中有多种方式定义entry
属性。
Single Entry (Shorthand) Syntax
Usage: entry: string|Array<string>
webpack.config.js
const config = {
entry: './path/to/my/entry/file.js'
};
module.exports = config;
上下两段代码是等价的:
const config = {
entry: {
main: './path/to/my/entry/file.js'
}
};
当传递一个数组给entry会发生什么?
把含有多个文件路径的数组传递给entry
属性,就等同于创建了一个multi-main entry
。 当你想将多个依赖的文件添加到一起,并且将它们的依赖绘制到一个"chunk"中时,这十分有用。
当你倾向于为一个应用程序或拥有单入口点的tool快速创建webpack配置文件时,这是一个很好的选择。但该语法在拓展或升级配置上缺乏足够的灵活性。
Object Syntax
Usage: entry: {[entryChunkName: string]: string|Array<string>}
webpack.config.js
const config = {
entry: {
app: './src/app.js',
vendors: './src/vendors.js'
}
};
对象语法(object syntax)比较冗长,但这是在你的应用程序中定义entry或entries拓展性(scalable )最好的方式。
"Scalable webpack configurations"是能被重用并且能与其他部分配置相结合的事物。这是一项流行的技术,被用于分离环境问题,建立目标和运行时间(runtime)。然后使用专门的工具如
webpack-merge
将它们合并。
Scenarios(使用场景)
Below is a list of entry configurations and their real-world use cases(真实世界中的用例):
Separate App and Vendor Entries
//webpack.config.js
const config = {
entry: {
app: './src/app.js',
vendors: './src/vendors.js'
}
};
What does this do? At face value(表面上) this tells webpack to create dependency graphs starting at both app.js and vendors.js. These graphs are completely separate and independent of each other (完全分离,并且相互独立)(there will be a webpack bootstrap in each bundle). This is commonly seen with single page applications(这在单页应用中很常见) which have only one entry point (excluding vendors)(除了vendors外,只有一个entry piont).
Why? This setup(设置) allows you to leverage(利用) CommonsChunkPlugin
and extract any vendor references from your app bundle into your vendor bundle(从app bundle中提取任何vendor引用到vendor bundle中), replacing them with __webpack_require__()
calls.
If there is no vendor code in your application bundle, then you can achieve(获得) a common pattern(模式) in webpack known as long-term vendor-caching.
可以考虑移除这个方案,使用DllPlugin取代,DllPlugin提供更好的vender-splitting。
Multi Page Application
//webpack.config.js
const config = {
entry: {
pageOne: './src/pageOne/index.js',
pageTwo: './src/pageTwo/index.js',
pageThree: './src/pageThree/index.js'
}
};
What does this do? We are telling webpack that we would like 3 separate dependency graphs (like the above example).
Why? In a multi-page application, the server is going to fetch a new HTML document for you. The page reloads this new document and assets are redownloaded. However, this gives us the unique opportunity to do multiple things:
Use CommonsChunkPlugin
to create bundles of shared application code between each page. Multi-page applications that reuse a lot of code/modules between entry points can greatly benefit from these techniques, as the amount of entry points increase.
As a rule of thumb(根据经验): for each HTML document use exactly one entry point.