webpack-dev-server 和 html-webpack-plugin的使用

webpack-dev-server的作用:自动编译

1、webpack-dev-server的使用

  1)cnpm i webpack-dev-server -D

  2)在package.json中配置:

  3)终端中输入命令:npm run dev

   4)浏览器访问http://localhost:8080/

  output file[main.js]托管到“/”,所以可以通过地址http://localhost:8080/main.js来访问

  在package.json中配置webpack-dev-server时常用的参数:

"dev": "webpack-dev-server --open --port 3000 --hot --host 127.0.0.1"

  --open: 自动编译完后打开浏览器

  5)修改index.html引入main.js

<script src="/main.js"></script>

2、html-webpack-plugin插件的使用

  1)cnpm i html-webpack-plugin

  2)webpack.config.js

var path = require('path')
// 导入在内存中自动生成index页面的插件 const HtmlWebPackPlugin = require('html-webpack-plugin') const htmlPlugin = new HtmlWebPackPlugin({ template: path.join(__dirname, './src/index.html'), filename: 'index.html' // 生成的内存中首页的名称 }); module.exports = { mode: 'development', plugins: [ htmlPlugin ] }

  3)npm run dev,自动打开浏览器访问主页index.html

   查看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>主页</title>
    <!-- <script src="../dist/main.js"></script> -->
    <!-- <script src="/main.js"></script> -->
</head>
<body>
    首页
    <div id="app"></div>
<script type="text/javascript" src="main.js"></script></body>
</html>

   插件自动添加一行代码:<script type="text/javascript" src="main.js"></script></body>

原文地址:https://www.cnblogs.com/xy-ouyang/p/11986373.html