1

这篇文章的学习总结。
思维导图
webpack工作流程:

1. 配置entry,output.

output的配置要注意pubilcPath这个属性,这个属性指明在浏览器中如何加载生成的打包文件。这个属性在加载额外的代码块(使用代码分隔),加载图片(通过require)等静态资源的时候特别有用。

官方文档:The publicPath specifies the public URL address of the output files when referenced in a browser.

StackOverflow:When executed in the browser, webpack needs to know where you'll host the generated bundle. Thus it is able to request additional chunks (when using code splitting) or referenced files loaded via the file-loader or url-loader respectively.
For example: If you configure your http server to host the generated bundle under /assets/ you should write: publicPath: "/assets/"

    entry: './src',
    output: {
        path: 'builds',
        filename: 'bundle.js',
        publicPath: 'builds/'
    },

2. 配置loader:

  • 针对html:html-loader将html作为字符串导出,请求静态资源。

  • 针对CSS:

    • style-loader将样式以<style>的形式插入html

    • css-loader解析样式文件中的依赖关系并返回css代码;

    • sass-loader解析sass.

  • 针对JS:babel等,将ES6 => ES5.

  • 针对图片:

    • file-loader将文件产出到output并且返回相对url。

    • url-loader与前一个作用类似,当文件大小小于limit时返回Data Url。

    一般来说,style!css链式使用,file-loaderurl-loader就同时使用。当文件比较小时,就通过url内联。

module:{
        loaders: [
            {
                test: /\.html$/,
                loader: 'html'
            },
            {
                test: /\.js$/,      //匹配项
                loader: 'babel',
                include: __dirname + '/src', //必须匹配的位置,相反exclude属性为不匹配该项
                query:{
                    presets: 'es2015'
                }
            },
            {
                test: /\.scss$/,
                loader: 'style!css!sass' //也可以写作loaders:['style','css','sass']
            }
        ]
    }

3. 代码分割:

- 使用CommonJS:`require.ensure(dependencies, callback)`;

- 使用ES6:
    //ES6:
    require.ensure([], function(require) {
      let contacts = require('./contacts')
    })   
//按需加载:当页面中有a元素时,才加载Button。可在Chrome devtool network中查看
if (document.querySelectorAll('a').length) {
   require.ensure([], () => {
       const Button = require('./Components/Button').default
       const button = new Button('google.com')
       button.render('a')
   })
    }

4. 配置插件:

- 分割代码时提取公共部分:CommonsChunkPlugin
  配置`output.chunkFilename:'[name]-[chunkhash].js'`
  
- 提取CSS生成独立的.css文件:extract-text-webpack-plugin
  注意:1)默认只提取最初的chunk,要提取所有的需要使用allChunks:true
       2)webpack版本1和版本2的配置不一样
    const webpack = require('webpack')
    const ExtractTextPlugin = require('extract-text-webpack-plugin')
    new webpack.optimize.CommonsChunkPlugin({
        name: 'main', //将依赖转移到主文件中
        children: true, //在所有子文件中寻找以来
        minChunks: 2 //一个依赖出现多少次会被抽取
    }),
    new ExtractTextPlugin('bundle.css',{
        allChunks:true //所有chunk中的也提取出来
    }) //将css生成到styles.css中
    
    {
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract('style','css!sass'),
            // loader: 'style!css!sass' //也可以写作loaders:['style','css','sass']
        }

- 生产环境需要的插件:
    // This plugin looks for similar chunks and files
    // and merges them for better caching by the user
    new webpack.optimize.DedupePlugin(),

    // This plugins optimizes chunks and modules by
    // how much they are used in your app
    new webpack.optimize.OccurenceOrderPlugin(),

    // This plugin prevents Webpack from creating chunks
    // that would be too small to be worth loading separately
    new webpack.optimize.MinChunkSizePlugin({
        minChunkSize: 51200, // ~50kb
    }),

    // This plugin minifies all the Javascript code of the final bundle
    new webpack.optimize.UglifyJsPlugin({
        mangle:   true,
        compress: {
            warnings: false, // Suppress uglification warnings
        },
    }),

5. 运行:

- 查看隐藏模块:`--display-modules`
- 查看模块和Chunks的对应关系: `--display-chunks`
- `webpack-dev-server --inline --hot`:第一个命令告诉Webpack在页面中包含HMR逻辑(代替在iframe中显示页面),第二个打开HMR。
devServer: {
 hot: true
}

6. 依赖关系的分析:webpack --profile --json > stats.json

以json格式生成profile输出到stats.json文件中。在这里这里查看。

7. 错误集锦:

  1. 安装sass-loader node-sass后运行webpack报错:

ERROR in dlopen(/Users/yawenina/Desktop/Codes/webpack-starter/node_modules/node-sass/vendor/darwin-x64-47/binding.node, 1): no suitable image found.  Did find:
           /Users/yawenina/Desktop/Codes/webpack-starter/node_modules/node-sass/vendor/darwin-x64-47/binding.node: truncated mach-o error: segment __TEXT extends to 1212416 which is past end of file 713264
 @ ./src/component/Button.scss 4:14-123

解决方案:运行npm rebuild node-sass


Yawenina
2.3k 声望117 粉丝

« 上一篇
JS学习总结
下一篇 »
面试问题集锦