安装webpack过程略过,同学可自行查看上一篇文章.
1.在项目目录下新建文件webpack.config.js
1 | module.exports = { |
这个一个符合CommonJS风格的module
2.简单的配置之后就可以运行打包。
1 | webpack |
webpack就会读取配置文件webpack.config.js
,build并生成app.bundle.js
3.还可以依赖插件,通过loader加载不同格式的文件
1 | const webpack = require('webpack'); |
4.使用jQuery和jQuery插件
如上面的代码plugins:
1 | lugins: [ //全局变量不用require |
对于不支持CommonJS规范的模块,需要安装 imports-loader
1 | //app.js |
config文件说明
entry
配置要打包的文件的入口;可以配置多个入口文件,下面会有介绍。
resolve
配置文件后缀名(extensions),除了js,还有jsx、coffee等等。
alias配置项,可以为常用模块配置改属性,可以节省编译的搜索时间。例如:
1 | resolve:{ |
output
配置输出文件的路径,文件名等。
module(loaders)
配置要使用的loader。对文件进行一些相应的处理。比如babel-loader可以把es6的文件转换成es5。
大部分的对文件的处理的功能都是通过loader实现的。loader就相当于gulp里的task。loader可以用来处理在入口文件中require的和其他方式引用进来的文件。loader一般是一个独立的node模块,要单独安装。
loader配置项:
1 | test: /\.(js|jsx)$/, //注意是正则表达式,不要加引号,匹配要处理的文件 |
目前已有的loader列表:https://webpack.github.io/docs/list-of-loaders.html
一个module的例子:
1 | module: { |
plugins
顾名思义,就是配置要使用的插件。plugin是比loader功能更强大的插件,能使用更多的wepack api。来看一个使用plugin的例子:
1 | plugins: [ |
目前已有的plugins列表:http://webpack.github.io/docs/list-of-plugins.html
可以暴露成全局变量的2个配置 ,引用国际友人的解释。来源
externals
ProvidePlugin
It’s both possible: You can include libraries with a <script>
(i. e. to use a library from a CDN) or include them into the generated bundle.
If you load it via <script>
tag, you can use the externals option to allow to write require(…) in your modules.
Example with library from CDN:
1 | <script src="https://code.jquery.com/jquery-git2.min.js"></script> |
Example with library included in bundle:
1 | copy `jquery-git2.min.js` to your local filesystem |
The ProvidePlugin
can map modules to (free) variables. So you could define: “Every time I use the (free) variable xyz inside a module you (webpack) should set xyz
to require("abc")
.”
Example without ProvidePlugin
:
1 | // You need to require underscore before you can use it |
Example with ProvidePlugin:
1 | plugins: [ |
Summary:
Library from CDN: Use <script>
tag and externals
option
Library from filesystem: Include the library in the bundle. (Maybe modify resolve options to find the library)externals
: Make global vars available as moduleProvidePlugin
: Make modules available as free variables inside modules