//使用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可以立即更新到瀏覽器上,項目配置成功!