Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Minification and more #14

Merged
merged 10 commits into from
Aug 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 52 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ yarn add esbuild-loader --dev

## Usage

### Transpiling
In `webpack.config.js`:

```js
Expand All @@ -24,19 +25,65 @@ module.exports = {
test: /\.[jt]sx?$/,
loader: 'esbuild-loader',
options: {
// All options are optional
target: 'es2015', // default, or 'es20XX', 'esnext'
jsxFactory: 'React.createElement',
jsxFragment: 'React.Fragment',
sourceMap: false // Enable sourcemap
},
},
{
test: /\.tsx$/,
loader: 'esbuild-loader',
options: {
loader: 'tsx',
target: 'es2015',
},
},
],
},
plugins: [
new ESBuildPlugin()
]
}
```

### Minifying

In `webpack.config.js`:

```js
const { ESBuildPlugin, ESBuildMinifyPlugin } = require('esbuild-loader')

module.exports = {
optimization: {
minimize: true,
minimizer: [
new ESBuildMinifyPlugin()
],
},
plugins: [new ESBuildPlugin()],

plugins: [
new ESBuildPlugin()
],
}
```


## Options

### Loader
The loader supports options from [esbuild](https://github.com/evanw/esbuild#command-line-usage).
- `target` `<String>` (`es2015`) - Environment target (e.g. es2017, chrome80, esnext)
- `loader` `<String>` (`js`) - Which loader to use to handle file. Possible values: `js, jsx, ts, tsx, json, text, base64, file, dataurl, binary`
- `jsxFactory` `<String>` - What to use instead of React.createElement
- `jsxFragment` `<String>` - What to use instead of React.Fragment
- Enable source-maps via [`devtool`](https://webpack.js.org/configuration/devtool/)

### MinifyPlugin
- `minify` `<Boolean>` (`true`) - Sets all `--minify-*` flags
- `minifyWhitespace` `<Boolean>` - Remove whitespace
- `minifyIdentifiers` `<Boolean>` - Shorten identifiers
- `minifySyntax` `<Boolean>` - Use equivalent but shorter syntax
- `sourcemap` `<Boolean>` (defaults to Webpack `devtool`)- Whether to emit sourcemaps


## License

MIT &copy; [EGOIST (Kevin Titor)](https://github.com/sponsors/egoist)
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,24 @@
"author": "EGOIST",
"license": "MIT",
"scripts": {
"test": "jest --env node"
"test": "jest --env node",
"lint": "prettier --write src test/*.js"
},
"files": [
"src"
],
"devDependencies": {
"@types/jest": "^25.2.1",
"jest": "^26.0.1",
"memfs": "^3.2.0",
"prettier": "^2.0.5",
"typescript": "^3.8.3",
"unionfs": "^4.4.0",
"webpack": "^4.43.0"
},
"dependencies": {
"esbuild": "^0.5.16",
"loader-utils": "^2.0.0"
"loader-utils": "^2.0.0",
"webpack-sources": "^1.4.3"
}
}
73 changes: 3 additions & 70 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,70 +1,3 @@
const path = require('path')
const esbuild = require('esbuild')
const { getOptions } = require('loader-utils')

const getLoader = (ext) => {
if (ext === '.json') {
return 'json'
}
return 'tsx'
}

module.exports = async function (source) {
const done = this.async()
const options = getOptions(this)
/** @type {import('esbuild').Service} */
const service = this._compiler.$esbuildService

if (!service) {
return done(
new Error(
`[esbuild-loader] You need to add ESBuildPlugin to your webpack config first`
)
)
}

try {
const ext = path.extname(this.resourcePath)

const result = await service.transform(source, {
target: options.target || 'es2015',
loader: getLoader(ext),
jsxFactory: options.jsxFactory,
jsxFragment: options.jsxFragment,
sourcemap: options.sourceMap,
})
done(null, result.js, result.jsSourceMap)
} catch (err) {
done(err)
}
}

module.exports.ESBuildPlugin = class ESBuildPlugin {
/**
* @param {import('webpack').Compiler} compiler
*/
apply(compiler) {
let watching = false

const startService = async () => {
if (!compiler.$esbuildService) {
compiler.$esbuildService = await esbuild.startService()
}
}

compiler.hooks.run.tapPromise('esbuild', async () => {
await startService()
})
compiler.hooks.watchRun.tapPromise('esbuild', async () => {
watching = true
await startService()
})

compiler.hooks.done.tap('esbuild', () => {
if (!watching && compiler.$esbuildService) {
compiler.$esbuildService.stop()
compiler.$esbuildService = undefined
}
})
}
}
module.exports = require('./loader')
module.exports.ESBuildPlugin = require('./plugin')
module.exports.ESBuildMinifyPlugin = require('./minify-plugin')
33 changes: 33 additions & 0 deletions src/loader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const path = require('path')
const { getOptions } = require('loader-utils')

async function ESBuildLoader(source) {
const done = this.async()
const options = getOptions(this)
/** @type {import('esbuild').Service} */
const service = this._compiler.$esbuildService

if (!service) {
return done(
new Error(
`[esbuild-loader] You need to add ESBuildPlugin to your webpack config first`
)
)
}

try {
const result = await service.transform(source, {
target: options.target || 'es2015',
loader: options.loader || 'js',
jsxFactory: options.jsxFactory,
jsxFragment: options.jsxFragment,
sourcemap: this.sourceMap,
sourcefile: this.resourcePath,
})
done(null, result.js, result.jsSourceMap)
} catch (err) {
done(err)
}
}

module.exports = ESBuildLoader
81 changes: 81 additions & 0 deletions src/minify-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
const { RawSource, SourceMapSource } = require('webpack-sources')

const isJsFile = /\.js$/i
const pluginName = 'esbuild-minify'

class ESBuildMinifyPlugin {
constructor(options) {
this.options = { ...options }

const hasMinify = Object.keys(this.options).some((k) =>
k.startsWith('minify')
)
if (!hasMinify) {
this.options.minify = true
}
}

/**
* @param {import('webpack').Compiler} compiler
*/
apply(compiler) {
const { options } = this

compiler.hooks.compilation.tap(pluginName, (compilation) => {
const service = compiler.$esbuildService

if (!service) {
throw new Error(
`[esbuild-loader] You need to add ESBuildPlugin to your webpack config first`
)
}

const { devtool } = compiler.options
const sourcemap =
options.sourcemap !== undefined
? options.sourcemap
: devtool && devtool.includes('source-map')

compilation.hooks.optimizeChunkAssets.tapPromise(
pluginName,
async (chunks) => {
const transforms = chunks.flatMap((chunk) => {
return chunk.files
.filter((file) => isJsFile.test(file))
.map(async (file) => {
const assetSource = compilation.assets[file]
const { source, map } = assetSource.sourceAndMap()

const result = await service.transform(source, {
...options,
sourcemap,
sourcefile: file,
})

compilation.updateAsset(file, () => {
if (sourcemap) {
return new SourceMapSource(
result.js || '',
file,
result.jsSourceMap,
source,
map,
true
)
} else {
return new RawSource(result.js || '')
}
})
})
})

if (transforms.length) {
await Promise.all(transforms)
}
}
)
})
}
}

module.exports = ESBuildMinifyPlugin
34 changes: 34 additions & 0 deletions src/plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const esbuild = require('esbuild')

class ESBuildPlugin {
/**
* @param {import('webpack').Compiler} compiler
*/
apply(compiler) {
let watching = false

const startService = async () => {
if (!compiler.$esbuildService) {
compiler.$esbuildService = await esbuild.startService()
}
}

compiler.hooks.run.tapPromise('esbuild', async () => {
await startService()
})

compiler.hooks.watchRun.tapPromise('esbuild', async () => {
watching = true
await startService()
})

compiler.hooks.done.tap('esbuild', () => {
if (!watching && compiler.$esbuildService) {
compiler.$esbuildService.stop()
compiler.$esbuildService = undefined
}
})
}
}

module.exports = ESBuildPlugin
Loading