webpack 学习第1集 - 安装与基本构建

2018-11-01  本文已影响0人  半斋

安装步骤

啥都不懂一切都按照官方教程来
webpack版本:4.23.1
webpack-cli版本:3.1.2

mkdir webpack-demo && cd webpack-demo
npm init -y
npm install --save-dev webpack
npm install --save-dev webpack-cli
// 一行代码
npm install webpack webpack-cli --save-dev
  {
    "name": "webpack-demo",
    "version": "1.0.0",
    "description": "",
+   "private": true,
-   "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "webpack": "^4.0.1",
      "webpack-cli": "^2.0.9"
    },
    "dependencies": {}
  }
  webpack-demo
  |- package.json
+ |- /dist
+   |- index.html
  |- /src
    |- index.js

index.html

<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <title>webpack-demo</title>
</head>
<body>
  <script src="main.js"></script>
</body>
</html>

index.js

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

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

  return element;
}

document.body.appendChild(component());

src:"源"代码,用于书写和编辑的代码
dist:"分发"代码,构建过程产生的代码最小化和优化后的“输出”目录,最终将在浏览器中加载

npm install --save lodash

//现在,在我们的脚本中 import lodash:

import _ from 'lodash';

模块详见

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

webpack.config.js

const path = require('path');

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

配置详见
PS: 不懂配置哇

  {
    "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"
    }
  }

现在,可以使用 npm run build 命令,来替代我们之前使用的 npx webpack 命令。注意,使用 npm 的 scripts,我们可以像使用 npx 那样通过模块名引用本地安装的 npm 包。这是大多数基于 npm 的项目遵循的标准,因为它允许所有贡献者使用同一组通用脚本(如果必要,每个 flag 都带有 --config 标志)。

上一篇下一篇

猜你喜欢

热点阅读