From ~729KB to ~24.2KB with Webpack Tree Shaking (~11.2KB Gzip)

The webpack 2 release came with built-in support for ES2015 modules (alias harmony modules) as well as unused module export detection. The new webpack 4 release expands on this capability with a way to provide hints to the compiler via the "sideEffects" package.json property to denote which files in your project are "pure" and therefore safe to prune if unused.

  • tree-shaking
      • workers
          • highlight.worker.js
        • components
            • pre.vue
          • nuxt.config.js
        // Core import
        import hljs from 'highlight.js/lib/highlight'
        
        addEventListener('message', async event => {
          const { language, code } = event.data
          // Language import
          const x = await (await import(`highlight.js/lib/languages/${language}`)).default
          // Register language
          hljs.registerLanguage(language, x)
          const result = hljs.highlightAuto(code)
          postMessage(result.value)
        })
        highlight.worker.js
        import webpack from 'webpack'
        import WorkerPlugin from 'worker-plugin'
        
        export default {
          build: {
            plugins: [
              new webpack.ContextReplacementPlugin(
                /highlight.js/lib/languages$/,
                new RegExp(`^./(${['javascript', 'dockerfile', 'bash', 'json'].join('|')})$`),
              ),
              new WorkerPlugin({
                // use "self" as the global object when receiving hot updates.
                globalObject: 'self'
              })
            ]
          }
        }
        nuxt.config.js
        
        
        
        export default {
          props: {
            content: {
              type: String,
              default: ''
            },
            language: {
              type: String,
              default: 'javascript'
            }
          },
          data () {
            return {
              highlight: this.content
            }
          },
          beforeMount () {
            if (process.browser) {
              const worker = new Worker('@/assets/workers/highlight.worker.js', { type: 'module' })
              worker.postMessage({
                language: this.language,
                code: this.highlight
              })
              worker.onmessage = event => this.highlight =  event.data
            }
          }
        }
        
        pre.vue
        Dalibor Gogic
        Dalibor Gogic

        Specializing in open web technologies and applications, evented architectures, accessibility and UX.

        DevOops
        Progressive Web App
        GET IT ON GOOGLE PLAY