[TOC]

基础概念和常见配置项介绍(一)

image.png

配置文件 webpack.config.js

const path = require("path")
module.exports = {
    mode: "development",
    entry: "./foo.js",
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: 'foo.bundle.js'
    }
}

mode模式

  • development 开发
  • production 生产 :代码需要压缩,图片需要优化

1.在配置文件中设置

module.exports = {
    mode:"development"
}

2.在命令行中设置

npx webpack --config webpack.config.entry.js --mode development

webpack 的入口(entry) 和 输出 (output)

webpack 从指定的入口文件开始,最终按照output设定输出固定内容的bundle。这个过程就用到了 loader 与 plugin , loader 是源代码的处理器,plugin解决的是loader处理不了的事情.

context

上下文,即项目打包的相对路径上下文。如果指定了 context=”/User/test/webpack” 那么我们设置的 entry 和 output 的相对路径都是相对于 /User/test/webpack 。context 值必须是一个绝对路径

module.exports = {
    context:'/Users/test/webpack'
}

Tips:在实际开发中 context 一般不需要配置,不配置则默认为 process.cwd() 即工作目录。

单文件入口

单文件入口可以快速创建一个只有单一文件入口的情况,例如 library 的封装,但是单文件入口的方式扩展配置灵活性较低。

module.exports = {
    entry:"path/to/my/entry/file.js"
}
//或者使用对象
module.exports = {
    entry:{
        main:"path/to/my/entry/file.js"
    }
}

多文件入口

module.exports = {
    entry:{
        home:"path/to/my/entry/home.js",
        search:"path/to/my/entry/search.js",
        list:"path/to/my/entry/list.js",
    }
}

Tips:对于一个 HTML 页面,我们推荐只有一个 entry ,通过统一的入口,解析出来的依赖关系更方便管理 和维护

output 输出

output 是指定了 entry 对应文件编译打包后的输出bundle.常用属性:

  • path : 输出的 bundle存放的路径,比如 dist output 等
  • filename: bundle的名称
  • publicPath :指定了一个在浏览器中被引用的URL地址

Tips:当不指定 output 的时候,默认输出到 dist/main.js ,即 output.path 是 dist , output.filename 是 main

一个webpack的配置,可以包含多个entry,但是只能有一个 output 。对于不同的 entry 可以通过 output.filename占位符语法来区分

module.exports = {
    entry: {
        home: "path/to/my/entry/home.js",
        search: "path/to/my/entry/search.js",
        list: "path/to/my/entry/list.js",
    },
    output: {
        filename: "[name].js",
        path: __dirname + '/dist'
    }
}

path/to/my/entry/home.js → dist/home.js
path/to/my/entry/search.js → dist/search.js
path/to/my/entry/list.js → dist/list.js

image.png

output.publicPath

对于使用