使用webpack

45 阅读2分钟

为什么需要webpack

传统前端项目html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- HTML code -->

    <!-- External dependencies -->
    <script type="text/javascript" src="path/to/jquery"></script>
    <!-- ... -->

    <!-- Our JavaScript files -->
    <script type="text/javascript" src="src/js/a.js"></script>
    <script type="text/javascript" src="src/js/b.js"></script>
    <script type="text/javascript" src="src/js/c.js"></script>
    <!-- ... -->

</body>
</html>

其中引入的JS文件可能最后会非常多,而其中的的依赖关系很难在开发和维护的过程中保持正确的引用关系,整个工程是比较脆弱的。 即便基于 Grunt Gulp 这些工具,会将JS文件打包成一个文件,但是其依赖的问题仍然没有解决。

基于webpack打包的html模版文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript" src="src/js/boundle.31cds131jddfeo.js"></script>
    <!-- ...boundle.js... -->
</body>
</html>

webpack将JS脚本等资源打包成一个或多个boundle,且已经解决了依赖关系的问题

webpack的最小可运行配置

webpack是在一个node环境下运行的工具,初始化node环境,下载使用webpack必要的工具 webpack webapck-cli

npm install webpack webpack-cli --save-dev

这时候直接运行 npx webpack 也是可以进行打包的,因为webpack有自己默认的一些打包配置,不过为了更好的控制其打包行为,我们要指定配置文件 webpack.config.js (在项目根目录下)

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: './dist'
    },
    mode: 'none'
}
  • entry: 入口文件(打包解析的起点)
  • output.filename: 打包结果文件名
  • output.path: 打包的目标路径(不存在的时候会新建)
  • mode: 打包的模式(不同环境打包配置会不相同,暂时不需要指定为none)

执行 npx webpack 时发现控制台会报错:

configuration.output.path: The provided value "./dist" is not an absolute path! -> The output directory as absolute path (required).

意思是说其打包的目标路径需要是个绝对路径,那么如何获得绝对路径呢?别忘了我们在一个node项目中,node有原生模块(path)支持路径相关操作

const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, './dist') 
    },
    mode: 'none'
}

为了方便起见,我们在package.json中配置npm的指令

"scripts": {
    "build": "webpack",
},

在控制台中可以使用 npm run build 来进行打包操作了