在项目中,我们常会用到css预处理器 ,如sass,less, stylus,书写css变得非常便捷;项目中一般会建立公共样式文件,存放公共样式、公共变量、项目主题、基础样式混合方法,但是在项目中使用这些变量的时候通常都要在每个页面style标签内用@import引入,繁琐,所以需要使用webpack的相关配置全局注入公共文件
sass 全局变量注入
为了使用sass,我们需要安装sass的依赖包
npm install --save-dev sass-loader
npm install --save-dev node-sass //sass-loader依赖于node-sass
1、使用sass-resources-loader工具引入
- 添加依赖
npm install sass-resources-loader --save-dev
- 在项目build文件夹里找到utils.js ,定位到下边代码
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
将scss: generateLoaders(‘sass’)进行修改
sass: generateLoaders('sass', {
indentedSyntax: true,
}),
scss: generateLoaders('sass').concat(
{
loader: 'sass-resources-loader',
options: {
//这里按照你的文件路径填写;多个文件时用数组的形式传入,如resources: [path.resolve(__dirname, '../src/styles/base/_variables.scss')]
resources: path.resolve(__dirname, '../src/styles/base/_variables.scss')
}
}),
当然也可以直接修改generateLoaders方法
function generateLoaders(loader, loaderOptions) {
const loaders = []
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
// loaders.push(MiniCssExtractPlugin.loader)
loaders.push({
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../../'
}
})
} else {
loaders.push('vue-style-loader')
}
loaders.push(cssLoader)
if (options.usePostCSS) {
loaders.push(postcssLoad