Skip to content

Instantly share code, notes, and snippets.

@qiulang
Last active September 5, 2018 05:23
Show Gist options
  • Save qiulang/a887b1d0ea86a0f4a158bdbb3b1f9941 to your computer and use it in GitHub Desktop.
Save qiulang/a887b1d0ea86a0f4a158bdbb3b1f9941 to your computer and use it in GitHub Desktop.

webpack 4 打包

网上能找到关于webpack的文章很多,这几篇讲得较清楚,并基于webpack4

  1. Learn Webpack by Example
  2. From Gulp to Webpack
  3. Webpack 4 Tutorial: from 0 Conf to Production Mode
  4. Webpack your bags, 老文章,但不少概念还适用。
  5. A tale of Webpack 4 and how to finally configure it in the right way,做了一个总结,把前面几篇提到要点都总结了一下

几点经验

  1. 之前代码把scr/lib下的代码单独做成一个npm包,让src/ui的文件引用,这时webpack和browserify有几点要注意:

    1. 设置babel loader的规则的时候不能 exclude: /node_modules/ 这和用browserify时候需要babelify把node_modules转码一样,因为我们包import和require混用,需要统一转成require.

    2. 如果对jsSipWrap.babelrc设置"modules":false就是不转commonjs,webpack同样会报错"export 'default' (imported as 'webApi') was not found in './getLoginInfo'

    3. browserify设置较隐晦,在SO回答了 需要在package.json 加一项 "browserify"

      "browserify": {
         "transform": [
           "babelify"
         ]
       }
    
  2. 为什么需要 html-loader & HtmlWebPackPlugin 一起:参见第一篇文章的HTML Processing 章节

  3. css是如何处理的:

    1. 最重要一点 import the CSS in the entry point,不然webpack不会处理css文件,很多这样的讨论 1,2,3,4
    2. 需要哪些loader,webpack 4 用 mini-css-extract-plugin
    3. 不需要 style-loader,不然报错window is not defined , css load readme给的例子用了,所以很容易出错。不需要是因为style-loader会“create inline style tag in HTML and place your css there” 但我们是在代码里设置样式,不是在html里。
    4. use 数组是从后往前处理, 比如 'css-loader','sass-loader'

we can specify multiple loaders in the use property by passing in an array of loader objects. The file then gets processed by each of the loaders starting with the last loader in the array and then ending with the first.

在entry的js文件里import css是最关键一步,也是最容易混淆的一步:我个人的理解是webpack主要是为了组件化的开发打包,组件化的开发css文件被import在js代码里是常见做法,然后再通过 extract plugin 把css单独提取出来。 "By default webpack will not bundle your css, it will create inline style tag in HTML and place your css there. For extract all your css and bundle into one css file you nee extract text plugin"

尝试用 multiple-entry-points 即专门对 css 加一个js文件,就是import一行,但觉得效果也不好。

直接import css在js里,gulp会报错

events.js:167
      throw er; // Unhandled 'error' event
      ^
SyntaxError: Unexpected token

解决这个问题的简单办法是用.transform({global: true}, require("browserify-css")) https://github.com/cheton/browserify-css

使用browserify-css始终感觉不是一个好办法。果然,改用sass没有相应browserify 插件,只能再找别的方案。但其实解决办法也简单,引入一步预处理,把这行删了再交给browserify处理就是。replace插件目前用browserify-replace 查看源代码实现很简单。

另,有的人因为 import css的写法反而弃用webpack,坚持gulp 。但对我来说,gulp远不如webpack方便断点调试,所以我推荐gulp。而且browserify 打包明显慢好多,文章里推荐browserify-incremental我没有精力和兴趣再实验了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment