1. 程式人生 > 實用技巧 >webpack打包初體驗

webpack打包初體驗

1.在目錄下執行

//生成的預設的package.json,採用預設答案
npm init -y

2.安裝webpack

npm install -D webpack-cli

3.新建 webpack.config.js

let path = require("path");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var MiniCssExtractPlugin = require("mini-css-extract-plugin");
var glob = require('glob');

let entries = getEntry();

module.exports = {
	mode: 'development',
	entry: entries,
	output: {
		filename: 'js/[name].[hash].js',
		path: path.resolve(__dirname, './dist')
	},
	devServer: {
		port: 3002,
		progress: true,
		contentBase: path.resolve('./dist')//專案啟動根目錄
	},
	plugins: [
		
		new MiniCssExtractPlugin({
			//輸出css到指定目錄
			filename: 'css/[name].css',
		})
	],
	module: {//模組
		rules: [
			{
				test: /\.css$/,
				use: [
					MiniCssExtractPlugin.loader,
					'css-loader',
				]//css不分離寫法
			},
		]
	}
}


//配置頁面
var entryObj = getEntry();
var htmlArray = [];

Object.keys(entryObj).forEach(function (element) {
	htmlArray.push({
		_html: element,
		title: '',
		chunks: [element]
	})
})

//獲取html-webpack-plugin引數的方法
var getHtmlConfig = function (name, chunks) {
	return {
		template: `./src/${name}/${name}.html`,
		filename: `${name}.html`,
		chunks: [name]
	}
}

console.log(htmlArray)
//自動生成html模板
htmlArray.forEach(function (element) {
	module.exports.plugins.push(new HtmlWebpackPlugin(getHtmlConfig(element._html, element.chunks)));
})


//動態新增入口
function getEntry () {
	var entry = {};
	//讀取src目錄所有page入口
	glob.sync('src/**/*.js').forEach(function (name) {
		var start = name.indexOf('src/') + 4;
		var end = name.length - 3;
		var eArr = [];
		var n = name.slice(start, end);
		n = n.split('/')[1];
		eArr.push('./' + name);
		eArr.push('babel-polyfill');
		entry[n] = eArr;
	})
	return entry;
}

3.檔案目錄

4.package.json配置項

{
  "name": "webpackdemo2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config webpack.config.js",
    "dev": "webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "glob": "^7.1.3",
    "html-webpack-plugin": "^4.4.1",
    "mini-css-extract-plugin": "^0.11.2",
    "css-loader": "^4.3.0",
    "webpack": "^4.44.2",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  },
  "dependencies": {
    "@babel/runtime": "^7.1.2",
    "babel-polyfill": "^6.26.0",
    "jquery": "^3.3.1"
  }
}





5.執行npm run build 即可生成打包檔案