Vue-cli 3.0如何通过vue.config.js给预处理器加载器传多个文件?
Hey there! Glad you asked—you absolutely don’t need to create a combined main.sass file to share multiple global mixins, variables, or utility files across your Vue components. You can configure this directly in vue.config.js using the built-in css.loaderOptions setting. Here’s how:
Core Approach: Use additionalData (or prependData for older Vue CLI versions)
Vue CLI lets you inject code directly into every single-file component’s <style> block via the additionalData option (for Vue CLI 4+; use prependData if you’re on Vue CLI 3). This lets you import multiple preprocessor files globally without repeating imports in every component.
Example for Sass (.sass syntax)
module.exports = { css: { loaderOptions: { sass: { // For Vue CLI 4+, use `additionalData` // For Vue CLI 3, replace with `prependData` additionalData: ` @import "@/sass/mixin.sass"; @import "@/sass/variables.sass"; @import "@/sass/utility-functions.sass"; ` } } } }
Example for SCSS (.scss syntax)
If you use the curly-brace SCSS syntax, target the scss key instead:
module.exports = { css: { loaderOptions: { scss: { additionalData: ` @import "@/sass/mixin.scss"; @import "@/sass/variables.scss"; ` } } } }
Key Notes
- Path Alias: The
@symbol is a default alias for your project’ssrcdirectory, so you don’t have to mess with messy relative paths like../../sass/.... - Order Matters: If your files have dependencies (e.g., variables need to load before mixins that use them), make sure to list the imports in the correct order.
- Other Preprocessors: This works for Less and Stylus too, with minor syntax changes:
- Less:
less: { additionalData: ` @import "@/less/variables.less"; @import "@/less/mixins.less"; ` } - Stylus:
stylus: { import: [ "@/stylus/variables.styl", "@/stylus/mixins.styl" ] }
- Less:
This approach keeps your project clean—no extra "wrapper" files needed, and all your global preprocessor assets are loaded automatically everywhere.
内容的提问来源于stack exchange,提问作者J. Doe

