webpack 起步

概念

官方解释:
本质上,webpack 是一个现代 JavaScript 应用程序的静态模块打包器(module bundler)。当 webpack 处理应用程序时,它会递归地构建一个依赖关系图(dependency graph),其中包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个 bundle。
自我理解:
webpack 用于管理资源(css,js,图标,字体等),解决依赖,构建为我们需要的前端资源
(说白了就是我们不用去关心复杂的依赖关系,由它来协助我们管理)。

基本安装

mkdir webpack-demo && cdwebpack-demo
npm init -y
npm install webpack webpack-cli --save-dev
npm install --save lodash
mkdir dist
mkdir src
touch dist/index.html
touch src/index.js

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>webpack起步</title>
  </head>
  <body>
    <script src="bundle.js" charset="utf-8"></script>
  </body>
</html>

index.js

import _ from 'lodash';

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

  // Lodash(目前通过一个 script 脚本引入)对于执行这一行是必需的
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  return element;
}

document.body.appendChild(component());

webpack.config.js

const path = require('path');

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

package.json

{
  "name": "webpack_test",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.39.2",
    "webpack-cli": "^3.3.7"
  },
  "dependencies": {
    "lodash": "^4.17.15"
  }
}

执行命令

npm run build

Hash: ff08386f744d6a405df0
Version: webpack 4.39.2
Time: 253ms
Built at: 08/28/2019 2:40:24 PM
    Asset      Size  Chunks             Chunk Names
bundle.js  70.7 KiB       0  [emitted]  main
Entrypoint main = bundle.js
[1] ./src/index.js 304 bytes {0} [built]
[2] (webpack)/buildin/global.js 472 bytes {0} [built]
[3] (webpack)/buildin/module.js 497 bytes {0} [built]
    + 1 hidden module

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

目录结构:

webpack-demo
|- package.json
|- webpack.config.js
|- /dist
  |- bundle.js
  |- index.html
|- /src
  |- index.js
|- /node_modules

浏览器访问 index.html绝对路径

Hello webpack
#成功啦

文档

https://www.webpackjs.com/guides/getting-started/

发布了236 篇原创文章 · 获赞 145 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/u011944141/article/details/100119412