1

最简单的webpack入门教程

 1 year ago
source link: https://blog.p2hp.com/archives/11036
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

这是一个简单的webpack入门教程

Webpack 是一个前端资源加载/打包工具。它将根据模块的依赖关系进行静态分析,然后将这些模块按照指定的规则生成对应的静态资源。

2 基本使用

使用webpack的前提是已经有了node环境,安装node就不赘述了

2.1 初始化

在空文件夹中使用命令行执行:

npm init -y

就会在当前目录下创建一个package.json文件

2.2 安装插件

还是在当前目录底下使用命令行执行:

npm install webpack webpack-cli --save-dev

2.3 配置项

在根目录底下创建src文件夹,里面创建index.js文件,随便写一行:

webp
index.js

然后还是在根目录底下创建一个webpack.config.js文件用来写webpack的配置项:

const path = require('path')

module.exports = {
  mode: 'development',
  // 入口文件
  entry: path.join(__dirname, 'src', 'index.js'),
  // 输出文件
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  }
}

以上是webpack最简单的配置

2.4 打包

在package.json文件下找到scripts选项写一条脚本命令:

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

当前package.json内容如下:

webp
package.json

然后在命令行中执行npm run build,webpack会开始打包,打包完成以后会生成一个dist文件夹,webpack会把src/index.js作为入口文件打包到dist底下,打开dist中的bundle.js(bundle.js也是在webpack.config.js中的filename配置命名的)可以看到之前在index.js中的内容:

webp
bundle.js

以上就是最基础的webpack使用方法

3 HtmlWebpackPlugin

html-webpack-plugin 插件专门为由webpack打包后的js提供一个载体,即一个HTML模板,里面通过script标签引用打包后的JS。

3.1 插件安装

在根目录底下打开命令行执行命令安装HtmlWebpackPlugin插件:

npm install html-webpack-plugin --save-dev

3.2 使用插件

在src目录底下创建index.html文件作为模板文件:

webp

在webpack.config.js文件中引入并使用插件:

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  mode: 'development',
  // 入口文件
  entry: path.join(__dirname, 'src', 'index.js'),
  // 输出文件
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'src', 'index.html'),
      filename: 'index.html'
    })
  ]
}

使用HtmlWebpackPlugin插件传入参数template是模板文件即刚刚创建的index.html,filename是打包出来的html文件名

3.3 打包

在命令行执行npm run build,在打包出来的dist文件夹中运行index.html文件,在控制台可以看到输出了bundle.js中的hello world:

webp
hello world

HtmlWebpackPlugin插件已经帮我们把bundle.js引入到了模板文件index.html中

4 webpack-dev-server

webpack-dev-server是webpack官方提供的一个小型Express服务器。使用它可以为webpack打包生成的资源文件提供web服务。

4.1 插件安装

在根目录底下打开命令行执行命令安装插件:

npm install webpack-dev-server --save-dev

4.2 使用插件

在webpack.config.js中增加配置:

  devServer: {
    // 端口
    port: 8090,
    // 静态资源目录
    static: path.join(__dirname, 'dist')
  }

在package.json的scripts中添加一条dev命令:

  "scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server"
  },

4.3 实现效果

在根目录下使用命令npm run dev,启动以后在命令行可以看到启动成功:

webp

由于我配置的端口号是8090,所以打开http://localhost:8090/,打开控制台可以看到hello world,然后直接在index.js中修改为console.log('hello world!!!'),然后直接看到在浏览器的控制台中直接生效了:

webp

https://github.com/chrischen0405/webpack-demo


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK