webpack-使用webpack-dev-middleware

1.环境创建和命令 

//基本环境
npm init -y
npm install --save-dev webpack
npm install --save-dev webpack-cli
npm install --save lodash
//本课环境
npm install --save-dev express webpack-dev-middleware
//运行的命令
npm run server

2.目录结构 

webpack-使用webpack-dev-middleware_第1张图片

3.源文件 



  
    起步
  
  
    
  

 

import _ from 'lodash';
 
function component() {
  var element = document.createElement('div');
 
  // Lodash(目前通过一个 script 脚本引入)对于执行这一行是必需的
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');
 
  return element;
}
 
document.body.appendChild(component());

 

{
  "name": "t9",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "server": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "express": "^4.17.1",
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11",
    "webpack-dev-middleware": "^3.7.2"
  },
  "dependencies": {
    "lodash": "^4.17.15"
  }
}
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');

const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);

// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath
}));

// Serve the files on port 3000.
app.listen(3000, function () {
  console.log('Example app listening on port 3000!\n');
});

 

const path = require('path');
 
module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  }
};

 

4 运行效果

webpack-使用webpack-dev-middleware_第2张图片

webpack-使用webpack-dev-middleware_第3张图片 

5.代码分析 

webpack-使用webpack-dev-middleware_第4张图片 

你可能感兴趣的:(webpack)