(一)
webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
module.exports = {
// entry: './src/index.js',
entry: { //入口有幾個文件,出口就會輸出幾個文件
app: './src/index.js',
print: './src/print.js'
},
output: {
// filename: 'bundle.js',
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
devServer: { //爲你提供了一個簡單的 web 服務器,並且能夠實時重新加載 npm install --save-dev webpack-dev-server
// contentBase: './dist',
contentBase: path.join(__dirname, "dist"),//告訴服務器從哪裏提供內容。只有在你想要提供靜態文件時才需要
compress: true, //一切服務都啓用gzip 壓縮
historyApiFallback: true,
hot: true, //啓用 webpack 的模塊熱替換特性
port: 9000 //指定要監聽請求的端口號
},
devtool: 'inline-source-map', //工具僅用於開發環境,請不要在生產環境中使用它們! 爲了更容易地追蹤錯誤和警告
module: {
rules: [{ //加載css npm install --save-dev style-loader css-loader
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{ //加載圖片 npm install --save-dev file-loader
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{ //加載字體
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
]
},
plugins: [ //設定 HtmlWebpackPlugin npm install --save-dev html-webpack-plugin
new HtmlWebpackPlugin({ //設定 HtmlWebpackPlugin,生成新的html替換舊的html npm install --save-dev html-webpack-plugin
title: 'Output Management'
}),
new CleanWebpackPlugin(['dist']), //清理 /dist 文件夾,重新生成新的dist文件夾
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
]
};
package.json:
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^1.0.1",
"file-loader": "^2.0.0",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.23.1",
"webpack": "^4.23.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10",
"webpack-merge": "^4.1.4"
},
"dependencies": {
"lodash": "^4.17.11"
}
}