02-04.使用Webpack配置文件

使用Webpack配置文件

使用npx webpack index.js对文件进行打包的时候,是使用的webpack的默认配置,对项目的入口文件进行打包。webpack为了提高易用性,提供了很多默认配置,但是随着项目复杂度的提升和其各工程各自的特点,使用默认配置已经不足以满足我们对项目工程化的需求,webpack支持使用自定义配置文件,对项目进行打包编译。

  • 使用npx webpack进行打包的时候,webpack会自动的在当前项目的根目录中寻找默认的配置文件webpack.config.js对项目进行打包
  • 使用npm webpack --config [filename]:指定特定的配置文件作为配置,使用webpack对项目进行打包

示例:使用配置文件打包项目(path:/source_code/02/02-04)

目录结构

  • src
    • index.js
    • header.js
    • sidebar.js
    • content.js
    • footer.js
  • index.html
  • webpack.config.js

文件内容:

  • webpack.config.js
const path = require('path')

module.exports = {
  // 定义入口文件
  entry: path.resolve(__dirname, "src/js/index.js"),
  // 定义打包后输入的文件 
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist")
  }
}
  • 编辑package.json,在scripts�中增加配置项:"bundle": "webpack --config ./source_code/02/02-04/webpack.config.js"
  • 执行npm run bundle,对代码进行打包编译。
  • 生成打包编译后的文件目录distdist/bundle.js,将index.html移动到dist目录中,修改引入的javascript为打包生成的bundle.js

你可能感兴趣的:(02-04.使用Webpack配置文件)