webpack-watch

*爱你&永不变心* 提交于 2020-01-25 14:08:57

1.环境准备和命令

// 环境准备
npm init -y
npm install --save-dev webpack
npm install --save-dev webpack-cli
npm install --save lodash
npm install --save-dev html-webpack-plugin
npm install clean-webpack-plugin --save-dev
// 观察明显(开始观察后,修改文件就会自动编译)
npm run watch

2.目录

3.代码文件 

dist/index.html(这个文件是自动生成的)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Output Management</title>
  </head>
  <body>
  <script type="text/javascript" src="app.bundle.js"></script>
  <script type="text/javascript" src="print.bundle.js"></script>
</body>
</html>

src/index.js 

import _ from 'lodash';
import printMe from './print.js';

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

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

  btn.innerHTML = 'Click me and check the console!';
  btn.onclick = printMe;
  element.appendChild(btn);

  return element;
}

document.body.appendChild(component());

 src/print.js

export default function printMe() {
    //console.log('I get called from print.js!');
    //alert('I get called from print.js!');
    alert('watch');
    //cosnole.error('I get called from print.js!');
  }

 package.json

{
  "name": "sourceMap",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --watch",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10"
  },
  "dependencies": {
    "lodash": "^4.17.15"
  }
}

 webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
//const CleanWebpackPlugin = require('clean-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
  entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
    devtool: 'inline-source-map',
    plugins: [
        //new CleanWebpackPlugin(['dist']),
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
          title: 'Output Management'
        })
      ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

4.运行效果

5.代码分析

 

6 npm run watch

7.修改文件自动编译

 

8.运行效果 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!