1. 程式人生 > >webpack 簡單配置

webpack 簡單配置

(一)

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"
  }
}