webpack 结合express启动本地项目

1、安装项目需要文件

yarn add webpack webpack-cli webpack-dev-middleware express html-webpack-plugin

2、项目配置如下

const HtmlWebpackPlugin=require(‘html-webpack-plugin‘)
const path = require(‘path‘)
module.exports = {
  entry:{
      main:‘./src/main.js‘  //根据目录,在src下新建main.js
  },
  plugins:[
   new HtmlWebpackPlugin({
       template:‘./src/public/index.html‘  //在src/public目录下新建html文件,body内容为<div id="root"></div>
   })
  ],
  output: {
    path: path.resolve(__dirname, ‘dist‘),
    filename: ‘[name].js‘
  }
}

3、main.js内容如下

let dom=document.querySelector(‘#root‘)
let text=document.createElement(‘div‘)
console.log(dom)
text.innerText=‘我是新创建的html2‘
dom.appendChild(text)

4、在项目根目录下建立server.js,内容如下

const express=require(‘express‘)
const webpackDevMiddleware=require(‘webpack-dev-middleware‘)
const config=require(‘./webpack.config‘)
const webpack=require(‘webpack‘)
const complier=webpack(config)   //webpack根据配置生成的编译文件

const app=express()
app.use(webpackDevMiddleware(complier))

app.listen(8080,()=>{
    console.log(‘8080端口已启动,地址为:http://localhost:8080‘)
})

5、package.json中配置命令

 "scripts": {
    "build": "webpack",
    "serve": "node server"
  },

6、运行yarn serve 就可以打开localhost:8080,查看编译效果了!

webpack 结合express启动本地项目

上一篇:CentOS 7.4 下 如何部署 AspNetCore 结合 consul


下一篇:crmeb多商户swoole端口被占用杀死进程的方法