337、Vue Loader学习笔记01 -【Vue Loader、使用预处理器】 2020.04.23

1、Vue Loader 是什么?

Vue Loader 是一个 webpack 的 loader,它允许你以一种名为单文件组件 (SFCs)的格式撰写 Vue 组件:

<template>
  <div class="example">{{ msg }}</div>
</template>

<script>
export default {
  data () {
    return {
      msg: 'Hello world!'
    }
  }
}
</script>

<style>
.example {
  color: red;
}
</style>

Vue Loader 还提供了很多酷炫的特性:

允许为 Vue 组件的每个部分使用其它的 webpack loader,例如在 <style 的部分使用 Sass 和在 <template 的部分使用 Pug;
允许在一个 .vue 文件中使用自定义块,并对其运用自定义的 loader 链;
使用 webpack loader 将 <style 和 <template 中引用的资源当作模块依赖来处理;
为每个组件模拟出 scoped CSS;
在开发过程中使用热重载来保持状态。
简而言之,webpack 和 Vue Loader 的结合为你提供了一个现代、灵活且极其强大的前端工作流,来帮助撰写 Vue.js 应用。

2、使用预处理器

在 webpack 中,所有的预处理器需要匹配对应的 loader。Vue Loader 允许你使用其它 webpack loader 处理 Vue 组件的某一部分。它会根据 lang 特性以及你 webpack 配置中的规则自动推断出要使用的 loader。

3、Sass

例如,为了通过 Sass/SCSS 编译我们的

npm install -D sass-loader node-sass

在你的 webpack 配置中:

module.exports = {
  module: {
    rules: [
      // ... 忽略其它规则

      // 普通的 `.scss` 文件和 `*.vue` 文件中的
      // `<style lang="scss">` 块都应用它
      {
        test: /\.scss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          'sass-loader'
        ]
      }
    ]
  },
  // 插件忽略
}

现在,除了能够 import ‘style.scss’,我们还可以在 Vue 组件中使用 SCSS:

<style lang="scss">
/* 在这里撰写 SCSS */
</style>

这个块里的任何内容都会被 webpack 当作在一个 *.scss 文件中一样被处理。

3.1 Sass vs SCSS

注意 sass-loader 会默认处理不基于缩进的 scss 语法。为了使用基于缩进的 sass 语法,你需要向这个 loader 传递选项:

// webpack.config.js -> module.rules
{
  test: /\.sass$/,
  use: [
    'vue-style-loader',
    'css-loader',
    {
      loader: 'sass-loader',
      options: {
        indentedSyntax: true,
        // sass-loader version >= 8
        sassOptions: {
          indentedSyntax: true
        }
      }
    }
  ]
}

3.2 共享全局变量

sass-loader 也支持一个 prependData 选项,这个选项允许你在所有被处理的文件之间共享常见的变量,而不需要显式地导入它们:

// webpack.config.js -> module.rules
{
  test: /\.scss$/,
  use: [
    'vue-style-loader',
    'css-loader',
    {
      loader: 'sass-loader',
      options: {
        // 你也可以从一个文件读取,例如 `variables.scss`
        // 如果 sass-loader 版本 < 8,这里使用 `data` 字段
        prependData: `$color: red;`
      }
    }
  ]
}

4、Less

npm install -D less less-loader

// webpack.config.js -> module.rules
{
  test: /\.less$/,
  use: [
    'vue-style-loader',
    'css-loader',
    'less-loader'
  ]
}

5、Stylus

npm install -D stylus stylus-loader
// webpack.config.js -> module.rules
{
test: /.styl(us)?$/,
use: [
‘vue-style-loader’,
‘css-loader’,
‘stylus-loader’
]
}

6、Babel

npm install -D babel-core babel-loader
// webpack.config.js -> module.rules
{
  test: /\.js?$/,
  loader: 'babel-loader'
}

Babel 的配置可以通过 .babelrc 或 babel-loader 选项来完成

7、参考文献

[01] Vue Loader介绍 - Vue Loader 官方文档

[02] 使用预处理器 - Vue Loader 官方文档

发布了350 篇原创文章 · 获赞 230 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/youyouwuxin1234/article/details/105703728