Skip to content

Commit

Permalink
feat(webpack): support webpack hmr (#947)
Browse files Browse the repository at this point in the history
Co-authored-by: liuq <lqadm@qq.com>
  • Loading branch information
aliuq and axiaoan committed May 7, 2022
1 parent 8238ae7 commit 1d52e8f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
3 changes: 3 additions & 0 deletions examples/vue-cli/vue.config.js
Expand Up @@ -9,5 +9,8 @@ module.exports = {
chainWebpack(config) {
config.module.rule('vue').uses.delete('cache-loader')
config.module.rule('tsx').uses.delete('cache-loader')
config.merge({
cache: false,
})
},
}
2 changes: 1 addition & 1 deletion packages/shared-integration/src/layers.ts
Expand Up @@ -27,7 +27,7 @@ export function getLayerPlaceholder(layer: string) {
return `#--unocss--{layer:${layer}}`
}

export const HASH_PLACEHOLDER_RE = /#--unocss-hash--\s*{\s*content\s*:\s*"(.+?)";?\s*}/g
export const HASH_PLACEHOLDER_RE = /#--unocss-hash--\s*{\s*content\s*:\s*\\*"(.+?)\\*";?\s*}/g
export function getHashPlaceholder(hash: string) {
return `#--unocss-hash--{content:"${hash}"}`
}
10 changes: 9 additions & 1 deletion packages/webpack/src/index.ts
Expand Up @@ -3,9 +3,12 @@ import type { ResolvedUnpluginOptions, UnpluginOptions } from 'unplugin'
import { createUnplugin } from 'unplugin'
import WebpackSources from 'webpack-sources'
import {
HASH_PLACEHOLDER_RE,
LAYER_MARK_ALL,
LAYER_PLACEHOLDER_RE,
createContext,
getHash,
getHashPlaceholder,
getLayerPlaceholder,
getPath,
resolveId,
Expand Down Expand Up @@ -58,8 +61,9 @@ export default function WebpackPlugin(
// serve the placeholders in virtual module
load(id) {
const layer = entries.get(getPath(id))
const hash = entries.get(`${id}_hash`)
if (layer)
return getLayerPlaceholder(layer)
return (hash ? getHashPlaceholder(hash) : '') + getLayerPlaceholder(layer)
},
webpack(compiler) {
// replace the placeholders
Expand All @@ -73,6 +77,7 @@ export default function WebpackPlugin(
for (const file of files) {
let code = compilation.assets[file].source().toString()
let replaced = false
code = code.replace(HASH_PLACEHOLDER_RE, '')
code = code.replace(LAYER_PLACEHOLDER_RE, (_, quote, layer) => {
replaced = true
const css = layer === LAYER_MARK_ALL
Expand Down Expand Up @@ -111,6 +116,9 @@ export default function WebpackPlugin(
const code = layer === LAYER_MARK_ALL
? result.getLayers(undefined, Array.from(entries.values()))
: result.getLayer(layer) || ''

const hash = getHash(code)
entries.set(`${path}_hash`, hash)
plugin.__vfs.writeModule(id, code)
})
}
Expand Down

0 comments on commit 1d52e8f

Please sign in to comment.