手動建立一些文件夾和文件javascript
用命令初始化html
cnpm init -y
安裝該練習所用到的依賴java
cnpm install webpack webpack-cli html-webpack-plugin -D
目錄結構以下webpack
index.jsweb
console.log("index在控制檯打印")
print.jsnpm
console.log("print在控制檯打印")
index.htmljson
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> </html>
package.json瀏覽器
{ "name": "webpack4-plugin", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack --config webpack.config.js", "start": "webpack-dev-server --open" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "html-webpack-plugin": "^3.2.0", "webpack": "^4.39.2", "webpack-cli": "^3.3.6" } }
webpack.config.jsapp
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './src/index.js', print: './src/print.js' }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'build') }, devServer:{ port:3000, contentBase:'./build', progress:true }, mode:'development', plugins: [ new HtmlWebpackPlugin({ title: 'webpack4使用plugin', // 生成的HTML文件的標題 template: path.resolve(__dirname, 'index.html') // 使用的模板路徑 }) ] }
若是用webpack-dev-server運行,則會自動打開瀏覽器,文件正常運行,可是並無打包生成的文件。緣由是webpack-dev-server主要調試用,生成的文件是在內存內,想要實際文件須要webpack編譯才能夠。webpack-dev-server
用webpack編譯
就打包生成了對應的文件夾及文件
build/index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script type="text/javascript" src="app.bundle.js"></script> <script type="text/javascript" src="print.bundle.js"></script> </body> </html>
手動打開打包生成build下的index.html控制檯也能正常且完整的打印出來