环境搭建(01):webpack

准备模块

  1. webpack
  2. webpack-cli
  3. webpack-dev-server
  4. html-webpack-plugin

webpack-dev-server

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

  • 为静态文件提供服务
  • 自动刷新和热替换(HMR)

安装

注意
webpack5.x和webpack-dev-server3不兼容
webpack-cli4.x和webpack-dev-server3不兼容

npm install webpack@4.44.2 webpack-cli@3.3.12 webpack-dev-server@3.11.0 html-webpack-plugin --save-d --registry=https://registry.npm.taobao.org

测试
结构

design-pattern-test
|-node_modules
|-release
|-src
    |-index.js
|-index.html
|-package.json
|-webpack.dev.config.js

index.js

alert(100);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>测试</p>
</body>
</html>

package.json

{
  "name": "design-pattern-test",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --config ./webpack.dev.config.js --mode development"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {},
  "devDependencies": {
    "html-webpack-plugin": "^4.5.0",
    "webpack": "^4.44.2",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}

webpack.dev.config.js

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

module.exports = {
    entry: './src/index.js',
    output: {
        path: __dirname + '/release',
        filename: 'bundle.js'
    },

    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html'
        })
    ],

    devServer: {
        contentBase: path.join(__dirname, './release'), //根目录
        open: true, //自动打开浏览器
        port: 9000
    }
}

测试

npm run dev

结果

自动打开http://localhost:9000/,并弹窗提示100
posted @ 2020-10-30 14:46  mrtransition  阅读(104)  评论(0)    收藏  举报