const path = require('path')
const fs = require('fs')
const { exec } = require('child_process')

function WebpackBuildDllPlugin(options) {
	const defaultOptions = {
		dllConfigPath: ''
	}
	this.options = { ...defaultOptions, ...options }
}

function logger(error, stdout, stderr) {
	console.log(stdout)
}

WebpackBuildDllPlugin.prototype.apply = function(compiler) {
	const options = this.options
	if (options.dllConfigPath) {
		const rootPath = process.cwd()
		const dllConfigPath = path.isAbsolute(options.dllConfigPath) ? options.dllConfigPath : path.join(rootPath, options.dllConfigPath)
		if (fs.existsSync(dllConfigPath)) {
			const dllConfig = require(dllConfigPath)
			const { entry, output } = dllConfig
			let outputPath = output.path
			if (path.isAbsolute(outputPath)) {
				outputPath = path.relative(rootPath, outputPath)
			}
			const firstEntryName = Object.keys(entry)[0]
			const filename = output.filename.replace('[name]', firstEntryName)
			const absolutePath = path.join(rootPath, outputPath, filename)
			if (fs.existsSync(absolutePath)) {
				exec(`cross-env NODE_ENV=${process.env.NODE_ENV || 'development'} webpack --config ${dllConfigPath}`, logger)
			}
		} else {
			throw Error('[webpack-build-dll-plugin] Not Found dllConfigPath.')
		}
	}

	compiler.plugin('compilation', compilation => {
		console.log('Executing pre-build scripts')
	})

	compiler.plugin('emit', (compilation, callback) => {
		console.log('Executing post-build scripts')
		callback()
	})

	compiler.plugin('done', function() {
		console.log('done')
	})
}

module.exports = WebpackBuildDllPlugin

@@ -177,16 +177,37 @@
 Path: ''
+,%0A%09%09forceBuild: false
 %0A%09%7D%0A%09thi
@@ -1042,24 +1042,47 @@
 ame)%0A%09%09%09if (
+options.forceBuild %7C%7C !
 fs.existsSyn
@@ -1218,20 +1218,16 @@
 er)%0A%09%09%09%7D
-%0A%09%09%7D
  else %7B%0A
@@ -1233,19 +1233,20 @@
 %0A%09%09%09
-throw Error
+%09console.log
 ('%5Bw
@@ -1274,323 +1274,135 @@
 in%5D 
-Not Found dllConfigPath.')%0A%09%09%7D%0A%09%7D%0A%0A%09compiler.plugin('compilation', compilation =%3E %7B%0A%09%09console.log('Executing pre-build scripts')%0A%09%7D)%0A%0A%09compiler.plugin('emit', (compilation, callback) =%3E %7B%0A%09%09console.log('Executing post-build scripts')%0A%09%09callback()%0A%09%7D)%0A%0A%09compiler.plugin('done', function() %7B%0A%09%09console.log('done')%0A%09%7D)
+DllReference is already builded.')%0A%09%09%09%7D%0A%09%09%7D else %7B%0A%09%09%09throw Error('%5Bwebpack-build-dll-plugin%5D Not Found dllConfigPath.')%0A%09%09%7D%0A%09%7D
 %0A%7D%0A%0A

Update Plugin