vue-loader是怎么运行的

特性

vue-loader提供给webpack使用。主要提供如下的几点特性css

  • 容许对Vue组件的每一个部分使用其余webpack加载器,例如,对于<style>是Sass预处理器,对于<template>能够是Pug模版引擎
  • 容许.vue文件中定制区块,这些定制块能够应用定制的加载程序链
<template>
  <div></div>
</template>

<script>
export default {
  
}
</script>

<style>
</style>

复制代码
  • <style><template>中引用的静态资产视为模块依赖项,并使用webpack加载器处理它们;
  • 模拟每一个组件的做用域CSS;
  • 在开发过程当中保持状态的热重载。

vue-loaderwebpack的结合为咱们提供了强大的工做流html

如何工做

接下来看看他是如何工做的vue

第一步

使用 @vue/component-compiler-utils 将SFC源代码解析为SFC描述符,而后,它为每种语言块生成一个导入,所以实际返回的模块代码以下所示webpack

// code returned from the main loader for 'source.vue'

// import the <template> block
import render from 'source.vue?vue&type=template'
// import the <script> block
import script from 'source.vue?vue&type=script'
export * from 'source.vue?vue&type=script'
// import <style> blocks
import 'source.vue?vue&type=style&index=1'

script.render = render
export default script

复制代码

代码都是从source.vue中导入的,可是域不一样。web

第二步,针对不一样语言

若是咱们想指定对应区块内的语言,好比<script lang="ts">, 这时候VueLoaderPlugin派上用场,对于webpack配置中的每一个模块规则,它都会建立一个针对相应Vue语言块请求的修改后的克隆。sass

假设已经为全部* .js文件配置了babel-loader。该规则将被克隆并应用于Vue SFC <script>块。在webpack内部,相似于下面的请求babel

import script from 'source.vue?vue&type=script'
复制代码

将被转换为markdown

import script from 'babel-loader!vue-loader!source.vue?vue&type=script'
复制代码

若是你为为* .scss文件配置了style-loader + css-loader + sass-loader。post

<style scoped lang="scss">
复制代码

vue-loader 将其转换为spa

import 'source.vue?vue&type=style&index=1&scoped&lang=scss'
复制代码

webpack 将其转换为

import 'style-loader!css-loader!sass-loader!vue-loader!source.vue?vue&type=style&index=1&scoped&lang=scss'
复制代码

第三步

处理扩展的请求时, vue-loader会被再次调用,此次webpack加载程序会注意到请求具备查询而且仅针对特定的块,选择目标块的内部内容,并将其传递给匹配的目标装载程序。

第四步,转换

对于<script>块,转换基本结束,对于<template><style> 块来讲,还有一些额外的任务须要执行。

  • 须要使用Vue模板编译器来编译模板

  • 须要在css-loader执行前, 对<style scoped>块进行处理

从技术上讲,这些是额外的装载机(templateLoader,stylePostLoader),须要注入扩展的加载程序链中,若是最终用户必须本身配置,那将很是复杂,因此 VueLoaderPlugin也注入了全局的加载器来拦截<template><style> 的块请求,并注入必要的装载机最终请求以下所示。

// <template lang="pug">
import 'vue-loader/template-loader!pug-loader!vue-loader!source.vue?vue&type=template'

// <style scoped lang="scss">
import 'style-loader!css-loader!vue-loader/style-post-loader!sass-loader!vue-loader!source.vue?vue&type=style&index=1&scoped&lang=scss'
复制代码
相关文章
相关标签/搜索