人人都该会点webpack(一):核心概念

307 阅读2分钟

初步了解webpack

webpack是一个JavaScript应用成语的静态模块打包器(static module bundler),用于映射到项目需要的每个模块,然后将所有这些依赖生成一个或多个bundle。
打包思路: 遍历源文件-->匹配规则-->打包

核心概念:

  • entry: 入口
  • ouput: 出口
  • loader: 编译器
  • plugins: 插件

entry[入口]

wepack的entry支持字符串,对象,数组

  • 单文件入口
 module.exports = {
 // one of below
     entry: `./src/main.js`
     entry: ['./src/hello.js']
     entty: {app: ['./src/world.js']}
 }
  • 多文件入口
module.exports = {
    entry: {
        'pages/after-order': `./src/pages/after-order/after-order.js`,
        'package-leader/index': `./src/pages/packge-leader/index/config.js`
    }
}

output[出口]

webapck的output指定了entry对应文件编译打包后输出的bundle
一个webpack配置, 可包含多个entry,但只能一个output.不同的entry可通过output.filename占位符语法来区别.

// 上文单入口
module.exports = {
 // one of below
     entry: `./src/main.js`
     entry: ['./src/hello.js']
     entty: {app: ['./src/world.js']},
 // output configurate
    output: {
        path: __dirname + '/dist',
        filename: '[name].js'
    }
 }
 // ./src/main.js ---> dist/main.js
 // ./src/hello.js ---> dist/hello.js
 // app: ['./src/world.js'] ---> dist/app.js
  • entry对象key值对应output的[name]并生成对应的文件夹;可以运用该特点实现小程序的分包要求.
module.exports = {
    entry: {
        'pages/after-order': `./src/pages/after-order/after-order.js`,
        'package-leader/index': `./src/pages/packge-leader/index/config.js`
    },
    output: {
        filename: '[name].js',
        path: __dirname + '/dist'
    }
}
// ---> dist/package-leader/index.js
// ---> dist/pages/after-order.js
  • webpack占位符
    • [hash],[chunkhash],[name],[id],[query],[function]
  • output.library

如果打包的目的是生成一个供别人使用的库,可以使用output.library来指定库名称,库的名称支持占位符和普通字符串

// 
module.exports = {
    output: {
        library: 'myLib' // '[name]',
        libratyTarget: 'var' // var,this,window,gloabal...
    }
}
注意: libraryTarget=global时,如果target=node才是global,默认target=web下global为window,保险起见可以使用this.

loader[解析处理器]

用于对模块的源代码进行转换,主要就是翻译的功能

// loader解析顺序从右往左(从后往前)
module.exports = {
    module: {
        {
            test: /\.(js|vue)$/,
            loader: 'eslint-loader',
            enforce: 'pre', // pre放最前面 post放最后面
            include: [resolve('src'), resolve('test')],
            options: {
              formatter: require('eslint-friendly-formatter')
            }
      },
    }
}

plugin插件

插件是 webpack 的支柱功能。webpack 自身也是构建于,你在 webpack 配置中用到的相同的插件系统之上! 插件目的在于解决 loader 无法实现的其他事。

module.exports = {
    // ...
     /* config.plugin('vue-loader') */
    plugins: [
        new VueLoaderPlugin()
    ]
}

总结

随着webpack4.0的到来,已经可以实现0配置启动项目,前端构建上手会越来越简单.

参考: