webpack小白入门详解

webpack从入门到单独搭建工程脚手架

Posted by Felix on July 13, 2019

webpack小白入门之基础概念【1-1】

环境搭建:安装Node.js 和 NPM

安装nvm https://github.com/nvm-sh/nvm

ps: nvm(Node.js Version Manager)也就是 Node.js 的包管理器,可以通过它方便安装和切换不同的Node.js版本。
  • Mac通过 curl 安装:curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash

  • Windows的安装方法 参考这里

检查node和NPM版本安装成功如下:

环境搭建:安装webpack和webpack-cli

创建空目录和package.json

  • mkdir webpack.1-1
  • cd webpack.1-1
  • npm init -y

安装 webpack 和 webpack-cli

  • npm install webpack webpack-cli –save-dev

  • 检查是否安装成功 cd node_modules.bin> webpack -v

在项目根目录下创建一个webpack.config.js 文件

'use strict';

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, 'dist'),// 打包的文件夹名
    filename: 'bundle.js'    // 打包的文件名
  },
  mode: 'production'

}

同时,在项目根目录下,创建src文件夹及其子文件helloworld.jsindex.js

helloworld.js

export function helloworld() {
  return 'hello webpack';
}

index.js

import { helloworld } from './helloworld';

document.write(helloworld());

这样一个简单的demo就完成了,在工程命令行中执行命令 webpack开始打包工程。

打包好的结果是这样的:

由于我们打包出来的dist文件夹下面是没有html文件的,所以我们在dist文件夹下新建一个index.html文件,然后将bundle.js引进来。然后在浏览器中打开,一个简单的demo效果就出来了。

总结一下:

'use strict';                                      

const path = require('path');                    
                                                   
module.exports = {                                     
   entry: './src/index.js', // 用来指定webpack的打包入口  // 如果是Windows电脑应该这样配置 entry: '../../src/index.js',                     
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'    // 打包的文件名
  },
  mode: 'production'

}

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Hello Webpack</title>
</head>

<body>
  <script src="./bundle.js" type="text/javascript"></script>
</body>

</html>

下一篇 webpack小白入门【1-2】webpack的基本用法之相关核心概念