这些应该是对在官网初学习的一个小总结吧~,大家可以去官网看较为详细的解释:
指南 | webpack 中文网 (webpackjs.com)

那我们话不多说,直接开始:

  1. 首先在nodeJs下创建一个webpack-demo文件夹,在其中调用命令行执行:

    1
    2
    npm init -y
    npm install webpack webpack-cli --save-dev
  2. 修改生成的package.json:删去package.json中的"main":"index.js",添加"private":true,得到的结果应该如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    {
    "name": "webpack-demo2",
    "version": "1.0.0",
    "description": "",
    "private": true,
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
    "webpack-cli": "^4.9.1"
    }
    }
  3. (创建一个bundle文件),在webpack-demo目录下创建src和dist文件夹

    src中放置书写和编辑的代码,即index.js

    dist中放置产生的代码最小化和优化后的“输出”目录,即index.html

    得到的项目逻辑为:

    1
    2
    3
    4
    5
    6
    webpack-demo
    |- package.json
    |- /dist
    |- index.html
    |- /src
    |- index.js
  1. 为了在index.js打包lodash依赖,需要在该webpack-demo文件夹所在的nodeJs下使用命令行执行:

    1
    npm install --save lodash
  2. index.js中写入:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import _ from 'lodash';

    function component() {
    var element = document.createElement('div');

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    return element;
    }

    document.body.appendChild(component());
  1. index.html中写入:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <!doctype html>
    <html>
    <head>
    <title>起步</title>
    </head>
    <body>
    <script src="./bundle.js"></script>
    </body>
    </html>
  1. 在目录下添加配置文件webpack.config.js(使输入高效):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    const path = require('path');

    module.exports = {
    entry: './src/index.js',
    output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
    }
    };
  2. 在该webpack-demo目录下用命令行输入如下内容,通过新配置文件再次执行构建:

    1
    npx webpack --config webpack.config.js

    得到的项目逻辑如下:

    1
    2
    3
    4
    5
    6
    7
    webpack-demo
    |- package.json
    |- webpack.config.js
    |- /dist
    |- index.html
    |- /src
    |- index.js

    到这一步,实现的效果就是打开index页面,会出现hello webpack

  1. 为了更快捷地运行webpack,我们可以在package.json添加npm运行脚本,即添加"build":"webpack"

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    {
    "name": "webpack-demo",
    "version": "1.0.0",
    "description": "",
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
    "webpack": "^4.0.1",
    "webpack-cli": "^2.0.9",
    "lodash": "^4.17.5"
    }
    }
  2. 最后一步在命令行执行:

    1
    npm run build

大功告成!