//使用webpack-dev-server,可以用http启动本地项目,方便发起http请求,file本地不能发请求
1、安装webpack、webpack-cli@3.3.12、webpack-dev-server
yarn add webpack webpack-cli@3.3.12 webpack-dev-server html-webpack-plugin
//webpack-cli安装高版本会报错,暂时不兼容,html-webpack-plugin在项目打包后生成html
2、webpack.config.js配置
const HtmlWebpackPlugin=require('html-webpack-plugin')
const path = require('path')
module.exports = {
entry:{
main:'./src/main.js'
},
devServer:{
contentBase: path.join(__dirname, "dist"),
compress: true,
port: 9000,
open:true
},
plugins:[
new HtmlWebpackPlugin({
template:'./src/public/index.html' //在这个目录下建立index.html文件,body里面加上<div id="root"></div>
})
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
}
}
3、在package.json中配置
"scripts": {
"build": "webpack",
"start": "webpack-dev-server"
},
4、在入口文件src/main.js中写上如下代码
let dom=document.querySelector('#root')
let text=document.createElement('div')
console.log(dom)
text.innerText='我是新创建的html3'
dom.appendChild(text)
5、yarn start ,可以见到项目启动,修改innerText可以立即更新到浏览器上,项目配置成功!
浙公网安备 33010602011771号