https://webpack.js.org/concepts/
webpack是一个为现代javascript application而生的module bundler:模块打包器。它支持非常多的配置,拥有强大的功能。但也正是因为这一点可能导致我们很多人一团雾水。在学习之前,先搞明白几个概念:
webpack经过编译后将会为你的application创建一张依赖图:dependency graph. 而这张依赖图的起点就被称之为: entry point. 这个entry point告诉webpakc从哪里开始根据扫描require(cmd), import(es6)等调用来不断描绘这张依赖图从而知道要打包哪些元素到最终的bundle中。
你可以将application的entry point看作 contextual root或者the first file to kick off your app
在webpack configuration object中,我们就使用entry这个属性来配置,最简单的例子:
module.exports = { entry: ‘./path/to/my/entry/file.js‘ };
entry point的设置有多种形式:
单个字符串:
const config = { entry: ‘./path/to/my/entry/file.js‘ }; module.exports = config;
数组字符串:
const config = { entry: [‘./path/to/lib/library.js‘,‘./path/to/my/entry/main.js‘] }; module.exports = config;
object syntax:
const config = { entry: { main: ‘./path/to/my/entry/file.js‘ } };
const config = { entry: { app: ‘./src/app.js‘, vendors: ‘./src/vendors.js‘ } };
const config = { entry: { pageOne: ‘./src/pageOne/index.js‘, pageTwo: ‘./src/pageTwo/index.js‘, pageThree: ‘./src/pageThree/index.js‘ } };
具体参考: https://webpack.js.org/concepts/entry-points/
一旦你已经将你的assets全部打包在一起了,我们仍然需要告诉webpack应该将我们的application bundle放到哪里.
这是通过output 属性来定义:(output也会有很多其他的属性,比如filename,path...)
var path = require(‘path‘); module.exports = { entry: ‘./path/to/my/entry/file.js‘, output: { path: path.resolve(__dirname, ‘dist‘), filename: ‘my-first-webpack.bundle.js‘ } };
Loader是webpack中非常重要的概念。webpack的目标是将项目中的所有assets都可以由webpack来打包,而不是直接放到浏览器那里(通过script tag, link tag css)去异步加载。(注意这也并不意味着这些assets都必须打包在一起,可以有些折中). webpack将任何一个文件(.css,.html,.less,.scss,.jpg...)都视作一个javascript module.然而,webpack仅能够理解javascript!
而Loaders就能够将这些webpack本身并不能够理解和认识的文件转化为一个module从而加入到bundle的依赖树中去。
loader相关的配置从高层上讲有两个目的:
1. 指定什么文件类型应该由一个Loader来transform (通过test 属性来完成)
2. 指定应该由哪个loader来transform作为bundle的输入
var path = require(‘path‘); const config = { entry: ‘./path/to/my/entry/file.js‘, output: { path: path.resolve(__dirname, ‘dist‘), filename: ‘my-first-webpack.bundle.js‘ }, module: { rules: [ {test: /\.(js|jsx)$/, use: ‘babel-loader‘} ] } }; module.exports = config;
上面的配置就像是我们要告诉webpack的编译器:
"
Hey webpack compiler,when you come across a path that resolves to a ‘.js‘ or ‘.jsx‘ file inside of a require
/import
statement, use the babel-loader
to transform it before you add it to the bundle
"
Loader本身只能对一个个文件来做transform,而plugin则通常用于对bundled module的chunks或者compilations执行一些特定的action并且定制部分功能。要使用一个plugin,我们需要require(),并且放在plugins属性中。
const HtmlWebpackPlugin = require(‘html-webpack-plugin‘); //installed via npm const webpack = require(‘webpack‘); //to access built-in plugins const config = { entry: ‘./path/to/my/entry/file.js‘, output: { filename: ‘my-first-webpack.bundle.js‘, path: ‘./dist‘ }, module: { rules: [ {test: /\.(js|jsx)$/, use: ‘babel-loader‘} ] }, plugins: [ new webpack.optimize.UglifyJsPlugin(), new HtmlWebpackPlugin({template: ‘./src/index.html‘}) ] }; module.exports = config;
原文:http://www.cnblogs.com/kidsitcn/p/6248119.html