Skip to content

Commit

Permalink
fix: webpack loader
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Jul 12, 2021
1 parent 74e17df commit 4f85c2a
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 9 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
dist
temp
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ export interface UnpluginOptions<UserOptions> {

export interface UnpluginInstance<UserOptions> {
rollup: (options?: UserOptions) => RollupPlugin;
webpack: { new(): any; };
webpack: (options?: UserOptions) => any;
}
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ export function getLoaderPath (name: string) {
mkdirSync(tempDir)
}

return join(tempDir, 'loader-' + name + '.js')
return join(tempDir, 'webpack-loader-' + name + '.js')
}
18 changes: 11 additions & 7 deletions src/webpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ import { getLoaderPath } from './utils'
export function getWebpackPlugin<UserOptions = {}> (
options: UnpluginOptions<UserOptions>
): UnpluginInstance<UserOptions>['webpack'] {
return class WebpackPlugin {
class UnpluginWebpackPlugin {
// eslint-disable-next-line no-useless-constructor
constructor (public userOptions?: UserOptions) {}

apply (compiler: any) {
const hooks = options.setup(this.userOptions)

Expand All @@ -21,20 +20,23 @@ export function getWebpackPlugin<UserOptions = {}> (
const loaderPath = getLoaderPath(options.name)

fs.writeFileSync(loaderPath, `
module.exports = async function(source) {
if (!this._compiler || !this._compiler.$unplugin) return source
module.exports = async function(source, map) {
const callback = this.async()
if (!this._compiler || !this._compiler.$unplugin)
return callback(null, source, map)
const plugin = this._compiler.$unplugin['${options.name}']
if (!plugin) return source
if (!plugin)
return callback(null, source, map)
const res = await plugin.transform(source, this.resource)
if (typeof res !== 'string') {
this.callback(null, res.code, res.map)
callback(null, res.code, res.map)
}
else {
this.callback(null, res)
callback(null, res, map)
}
}
`, 'utf-8')
Expand All @@ -52,4 +54,6 @@ module.exports = async function(source) {
}
}
}

return UserOptions => new UnpluginWebpackPlugin(UserOptions)
}

0 comments on commit 4f85c2a

Please sign in to comment.