webpack技术讲解及入门

webpack基本已经成为前端项目的标配构建工具了。

然而,在一个前端团队里面,除了架构师之外,其他开发者很难有机会在工作中完整的实现整个配置流程。

本篇文章是我在公司里面分享webpack及babel配置和插件开发的一个细节版本,

希望能让大家通过阅读本文,比较好的梳理webpack工具。

webpack的出现解决了什么问题

JavaScript自面世之后,就成为浏览器的标准脚本语言。

然而JS本身并没有提供python和java的package包、子模块的import等语法。

同时,前端代码还需要处理类似CSS、png、webfonts等非JS的文件。

在前端工程化大潮下,一个既能处理JS又能处理别的资源文件的加载器(bundler)亟待出现。

webpack就是这类解决方案中的杰出代表。

下面,我将按照如下的目录结构对webpack使用进行讲解。

1、webpack概述
2、一个简单而通用的webpack配置文件
3、webpack的配置文件解读
4、webpack常用的plugins及loader

1.webpack概述

webpack = module building system。

在webpack看来,所有的资源文件都是模块(module),只是处理的方式不同。

上面两句话就把webpack从top-level的角度讲清楚了。

关于webpack的使用,其实和我们平时开发业务产品是一个道理。

产品需求 ===> 代码设计 ===> 提供API给开发者使用。

webpack解决的需求点就是如何更好的加载前端模块。

这里我用了模块二字,是因为webpack从JS出发,将所有的文件看做它要处理的模块。

webpack本身并不关心这个模块是什么,它只是调度配置文件中对模块处理的方式来完成这一切,而不必纠结文件类型。

比如我们会在项目中使用ES6/7的语法来编写JS代码,

于是我们只需要配置babel-loader即可处理这种JS。

比如我们需要加载html文件获取html字符串,

于是我们只需要配置raw-loader即可拿到对应文件的字符串。

比如我们需要将sass/less文件预编译成css,

于是我们只需要配置sass-loader/less-loader即可处理。

webpack提供了一套API接口,开发者只需要按照它提供的规范照着做就行了。

对于开发者来说,除了需要阅读英语文档能力和nodeJS之外,webpack的学习门槛真的不高。

2.一个简单而通用的webpack配置文件

我们以如下的 webpack.config文件来进行分析

var webpack = require("webpack");
var DefinePlugin = require('webpack/lib/DefinePlugin');
module.exports =  { 
        context:process.cwd(),
        watch: true,
        entry: './index.js',
        devtool: 'source-map',
        output: {
            path: path.resolve(process.cwd(),'dist/'),
            filename: '[name].js'
        },
        resolve: {
            alias:{ jquery: process.cwd()+'/src/lib/jquery.js', }
        },
        plugins: [
            new webpack.ProvidePlugin({
                $: 'jquery',
                _: 'underscore',
                React: 'react'
            }),
            new DefinePlugin({
              'process.env': {
                'NODE_ENV': JSON.stringify('development')
              }
            })
        ],
        module: {
            loaders: [{
                test: /\.js[x]?$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            },  {
                test: /\.less$/,
                loaders:['style-loader', 'css-loader','less-loader']
            }, {
                test: /\.(png|jpg|gif|woff|woff2|ttf|eot|svg|swf)$/,
                loader: "file-loader?name=[name]_[sha512:hash:base64:7].[ext]"
            }, {
                test: /\.html/,
                loader: "html-loader?" + JSON.stringify({minimize: false })
            } ]
        }
    };

这个简单的webpack配置文件,基本可以处理大多数的前端业务场景了。

通过配置plugins、module.loaders、entry、output基本可以构建一个兼容本地开发和生产环境的富应用web工程,下面针对以上的配置文件进行分析。

3. webpack的配置文件解读

  • module.loaders数组
    [{
        test: /\.js[x]?$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
    }]

比如有个文件require(‘index.jsx’), webpack会根据文件名是否满足test字段的正则来决定是否使用babel-loader来处理文件。 exclude则是告诉webpack不需要对node_modules目录进行处理

  • resolve对象
  resolve: {
            alias:{ jquery: path.resolve(process.cwd(),'src/lib/jquery.js')},
            extensions:['.js','.json']
        }

resolve对象是在webpack预编译时,就加载进整个webpack编译的配置中的。

比如alias会建立文件标识符映射表

require('jquery')==> require('/Users/**/src/lib/jquery.js')
  • plugins数组
    /**
    比如有个文件代码中存在process.env对象,则process.env将会被替换成上面的{
        'NODE_ENV': JSON.stringify('development')
    }    console.log(process.env)==>console.log(({"NODE_ENV":'development'}))
    */

    plugins: [new DefinePlugin({
        'process.env': {
            'NODE_ENV': JSON.stringify('development')
            }
        })]

关于这个配置文件,读者如果有疑问,可以直接在评论区留言,我会尽快回复,这里就不赘述了。

更进一步的webpack配置含义可以参考我的github博客webpack编译流程漫谈

4. webpack常用的loaders和plugins

关于loader这块呢,webpack官方给出了非常详尽的解决方案,基本不用开发者再去开源社区上寻找。前端资源loaders列表

关于plugins这块,除了webpack官方推荐的几款plugins外,社区上也有非常多不错的插件。webpack内置的plugins列表

经过多个前端项目搭建实践下,笔者认为如下几款plugins是非常不错的。

1、代码优化之:

CommonsChunkPlugin – 抽取公共代码

UglifyJsPlugin – 压缩混淆代码

2、 依赖注入之:

DefinePlugin – 自由变量注入

ProvidePlugin – 模块变量标示符注入

3、 文件抽取之:

file-loader – 传送font等文件

ExtractTextPlugin – 抽取css文件

4、 开发体验优化之:

WebpackNotifierPlugin – 编译完成动态通知

HtmlWebpackPlugin – 采用模板引擎形式注入到html文件,让开发更加easy

5、 目录/文件拷贝之:

CopyWebpackPlugin – 目录及文件拷贝

5.webpack总结

本篇文章对webpack的讲解主要集中在API层面。

另外,关于更加深入的webpack的编译流程, 我几个月前写过一篇博客webpack编译流程漫谈,可以供大家参考学习。

作者:slashhuang

42 thoughts on “webpack技术讲解及入门”

  1. I need to to thank you for this wonderful read!!

    I absolutely enjoyed every little bit of it. I have
    got you book marked to check out new things you post…

  2. This is a topic which is near to my heart… Take care! Exactly where are your contact details though?

  3. Hi my friend! I wish to say that this post is amazing, great written and come with approximately all vital infos.
    I would like to look extra posts like this .

  4. Excellent way of explaining, and fastidious article to take facts on the topic of my presentation topic, which i am going to present in institution of higher education.

  5. My brother suggested I might like this website.
    He was entirely right. This post actually made my day.
    You can not imagine just how much time I had
    spent for this info! Thanks!

  6. I have been surfing online greater than three hours today, but I never
    discovered any fascinating article like yours. It is beautiful
    value sufficient for me. In my view, if all website owners and bloggers made good content material as you did, the web will likely be a lot more useful than ever before.

  7. I’m not sure why but this blog is loading extremely slow
    for me. Is anyone else having this problem or is it a issue on my end?
    I’ll check back later on and see if the problem still exists.

  8. Hi there I am so grateful I found your site, I really found you by accident, while I was researching
    on Yahoo for something else, Regardless I am here now and would
    just like to say thanks for a remarkable post and a all round interesting blog (I also love the
    theme/design), I don’t have time to read through it all
    at the minute but I have bookmarked it and also included your RSS feeds, so when I
    have time I will be back to read more, Please do keep up the excellent b.

  9. I would like to express my thanks to you just for bailing me out of such a condition. As a result of surfing around through the search engines and coming across opinions which were not pleasant, I figured my entire life was well over. Living without the approaches to the issues you’ve sorted out by way of your main article content is a critical case, as well as those that could have negatively damaged my career if I had not come across your website. Your own personal competence and kindness in touching a lot of things was very useful. I don’t know what I would’ve done if I had not discovered such a stuff like this. I am able to now look forward to my future. Thanks a lot very much for this professional and effective guide. I won’t hesitate to suggest the sites to anyone who needs and wants tips on this area.

  10. hi!,I really like your writing so so much! proportion we be in contact more about your article on AOL?
    I need an expert in this area to unravel my problem.

    May be that is you! Having a look ahead to look you.

  11. Hey there! Would you mind if I share your blog with my twitter group?

    There’s a lot of people that I think would really appreciate
    your content. Please let me know. Thank you

  12. Thank you for your entire hard work on this web page. Betty enjoys working on internet research and it’s simple to grasp why. We all notice all regarding the dynamic way you present insightful guidelines on the web blog and therefore cause contribution from some others about this situation so our princess is without a doubt becoming educated so much. Take pleasure in the rest of the year. You’re the one conducting a good job.

  13. Just desire to say your article is as surprising. The clarity in your post is
    simply cool and i could assume you are an expert on this subject.

    Well with your permission allow me to grab your feed to keep updated with forthcoming post.
    Thanks a million and please keep up the gratifying work.

  14. I’m just writing to make you know what a helpful encounter my friend’s girl undergone reading through your web site. She came to understand numerous pieces, not to mention what it’s like to possess a marvelous helping heart to get most people just comprehend specific complicated issues. You truly did more than people’s expectations. Many thanks for coming up with these powerful, trusted, explanatory as well as cool thoughts on this topic to Julie.

  15. I am writing to make you know of the exceptional discovery my wife’s daughter went through studying your webblog. She came to find some pieces, which included what it is like to have a wonderful teaching character to get many people completely know several multifaceted subject areas. You actually surpassed visitors’ expected results. Thanks for imparting these necessary, trustworthy, educational not to mention fun guidance on your topic to Lizeth.

  16. I together with my friends happened to be viewing the excellent pointers located on the blog while instantly came up with a terrible feeling I had not thanked the website owner for those tips. All of the people are already for that reason excited to read them and already have undoubtedly been taking advantage of those things. Thanks for turning out to be very kind and then for having these kinds of awesome things millions of individuals are really desirous to learn about. My personal honest regret for not expressing appreciation to you earlier.

  17. I wish to show thanks to this writer for bailing me out of such a challenge. Just after researching through the search engines and getting strategies which are not pleasant, I assumed my entire life was done. Living minus the approaches to the difficulties you’ve fixed all through your good posting is a critical case, as well as ones that would have in a wrong way damaged my career if I hadn’t come across your blog post. Your main knowledge and kindness in maneuvering almost everything was priceless. I’m not sure what I would have done if I had not discovered such a subject like this. I am able to at this point relish my future. Thanks a lot very much for the high quality and effective help. I will not hesitate to propose your web site to any person who would need guide about this subject.

  18. I simply needed to appreciate you all over again. I do not know the things I would’ve implemented in the absence of those techniques contributed by you about such theme. It had been an absolute frustrating problem in my view, nevertheless taking a look at your professional manner you solved it took me to leap over joy. I am happy for your support and in addition wish you comprehend what an amazing job your are accomplishing teaching some other people via your website. I am sure you’ve never encountered all of us.

  19. Heya! I just wanted to ask if you ever have any problems with
    hackers? My last blog (wordpress) was hacked and I ended up losing several weeks
    of hard work due to no backup. Do you have any methods to
    stop hackers?

  20. I know this if off topic but I’m looking into starting my own blog and was wondering
    what all is needed to get set up? I’m assuming having
    a blog like yours would cost a pretty penny?
    I’m not very internet savvy so I’m not 100% positive.
    Any suggestions or advice would be greatly appreciated.
    Thanks 31muvXS cheap flights

  21. Howdy! I could have sworn I’ve been to your blog before but after looking at a few
    of the posts I realized it’s new to me. Anyhow, I’m definitely happy I
    found it and I’ll be book-marking it and checking back often! cheap flights 3gqLYTc

  22. Hi there I am so happy I found your blog, I really
    found you by accident, while I was researching on Digg for something else, Anyhow
    I am here now and would just like to say thanks for a fantastic post and a all round interesting blog (I
    also love the theme/design), I don’t have time to go through
    it all at the minute but I have saved it and also added
    your RSS feeds, so when I have time I will be back to read a lot more,
    Please do keep up the superb work.

  23. I precisely needed to thank you very much once again. I’m not certain the things I could possibly have tried without the actual points shared by you concerning my subject. It was before the alarming scenario in my opinion, but finding out a well-written fashion you handled that took me to jump over fulfillment. I’m just happy for this support and as well , trust you recognize what an amazing job you happen to be accomplishing instructing people by way of your web site. Most likely you have never come across all of us.

  24. Heya i’m for the first time here. I found this board
    and I in finding It truly useful & it helped me
    out a lot. I hope to provide something back and help others such as you aided me.

  25. Great post. I was checking constantly this blog and I’m impressed!
    Extremely useful information specially the last part 🙂 I care for
    such info much. I was looking for this certain info for a long time.
    Thank you and good luck.

  26. My husband and i got quite joyful Chris managed to do his researching because of the ideas he received using your web site. It is now and again perplexing to simply always be freely giving facts which the rest could have been selling. And we also keep in mind we have got the blog owner to thank for this. The main explanations you made, the straightforward web site menu, the friendships your site help promote – it’s many remarkable, and it’s letting our son and the family reason why that content is satisfying, and that’s tremendously fundamental. Thanks for everything!

  27. Hey! I know this is kind of off topic but I was wondering which blog platform are
    you using for this website? I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another
    platform. I would be fantastic if you could
    point me in the direction of a good platform.

  28. I simply had to thank you very much again. I do not know the things that I might have accomplished in the absence of these aspects revealed by you concerning this situation. Completely was a alarming scenario in my view, nevertheless noticing the specialised style you dealt with the issue took me to leap for joy. Now i am grateful for this support and even trust you really know what an amazing job you’re putting in training most people by way of your website. Most likely you’ve never met any of us.

  29. This is the perfect web site for anyone who would like to find
    out about this topic. You realize so much its almost hard to argue with you (not that I personally will need to…HaHa).
    You definitely put a fresh spin on a topic that has been written about for
    years. Excellent stuff, just wonderful!

  30. You really make it seem so easy with your presentation however I to find this
    topic to be really something which I believe I would by no means understand.

    It seems too complicated and extremely huge for me.

    I’m looking ahead for your subsequent submit, I will attempt to get the dangle of it!

  31. I would like to express my respect for your generosity giving support to men and women who actually need help with this important concept. Your real dedication to passing the solution across ended up being exceedingly invaluable and have consistently helped workers like me to achieve their targets. This invaluable publication can mean so much to me and a whole lot more to my office colleagues. Thank you; from all of us.

  32. Oh my goodness! a tremendous article dude. Thanks However I am experiencing situation with ur rss . Don抰 know why Unable to subscribe to it. Is there anyone getting equivalent rss problem? Anybody who is aware of kindly respond. Thnkx

  33. If some one needs expert view on the topic of running a blog afterward i advise him/her to pay a visit this blog, Keep up the pleasant
    job.

  34. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four e-mails with
    the same comment. Is there any way you can remove me from that service?
    Many thanks!

  35. Spot on with this write-up, I actually suppose this website needs much more consideration. I抣l probably be again to read much more, thanks for that info.

发表评论

电子邮件地址不会被公开。