GithubHelp home page GithubHelp logo

yenshih / style-resources-loader Goto Github PK

View Code? Open in Web Editor NEW
261.0 4.0 10.0 1.36 MB

CSS processor resources loader for webpack

License: MIT License

TypeScript 67.48% CSS 7.12% JavaScript 0.91% Less 6.75% Sass 5.84% SCSS 6.81% Stylus 5.09%
webpack loader style css sass scss less stylus inject resource

style-resources-loader's People

Contributors

yenshih avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

style-resources-loader's Issues

How to make style-resources-loader work in Storybook?

I'm trying to set up the style-resources-loader package into my vue project Storybook.

Here's my webpack.config.js file:

const path = require('path');

// This log returns the correct path of my file
console.log(path.resolve(__dirname, './src/assets/styles/01-utils/_mixins.scss'));

module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        loaders: ['style-loader', 'css-loader', 'sass-loader', {
          loader: 'style-resources-loader',
          options: {
            patterns: [
              path.resolve(__dirname, '../assets/styles/style.scss'),
              path.resolve(__dirname, '../assets/styles/01-utils/_mixins.scss'),
              path.resolve(__dirname, '../assets/styles/01-utils/_media-queries.scss'),
            ]
          }
        }],
        include: path.resolve(__dirname, '../')
      },
    ]
  },
};

I expect my component style file to work properly and recognise the mixin called inside it but it's not recognised during compilation.

 ERROR in ./src/components/01-atoms/Logo/Logo.vue?vue&type=style&index=0&lang=scss& (./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/sass-loader/lib/loader.js!./node_modules/style-resources-loader/lib??ref--3-3!./node_modules/vue-loader/lib??vue-loader-options!./src/components/01-atoms/Logo/Logo.vue?vue&type=style&index=0&lang=scss&)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):

  @include flex-absolute-center;
          ^
      No mixin named flex-absolute-center
      in /Applications/MAMP/htdocs/Perso/specify-share/src/components/01-atoms/Logo/Logo.scss (line 14, column 12)
 @ ./src/components/01-atoms/Logo/Logo.vue?vue&type=style&index=0&lang=scss& (./node_modules/style-loader!./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/sass-loader/lib/loader.js!./node_modules/style-resources-loader/lib??ref--3-3!./node_modules/vue-loader/lib??vue-loader-options!./src/components/01-atoms/Logo/Logo.vue?vue&type=style&index=0&lang=scss&) 2:14-374 21:1-42:3 22:19-379
 @ ./src/components/01-atoms/Logo/Logo.vue?vue&type=style&index=0&lang=scss&
 @ ./src/components/01-atoms/Logo/Logo.vue
 @ ./src/components/01-atoms/Logo/Logo.story.js
 @ ./src/components sync \.story\.js$
 @ ./.storybook/config.js
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./.storybook/config.js ./node_modules/webpack-hot-middleware/client.js?reload=true

ERROR in ./src/components/01-atoms/Logo/Logo.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/01-atoms/Logo/Logo.vue?vue&type=script&lang=js&)
Module not found: Error: Can't resolve '@/assets/icons/specify-logo.svg' in '/Applications/MAMP/htdocs/Perso/specify-share/src/components/01-atoms/Logo'
 @ ./src/components/01-atoms/Logo/Logo.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/01-atoms/Logo/Logo.vue?vue&type=script&lang=js&) 7:0-58 21:19-30
 @ ./src/components/01-atoms/Logo/Logo.vue?vue&type=script&lang=js&
 @ ./src/components/01-atoms/Logo/Logo.vue
 @ ./src/components/01-atoms/Logo/Logo.story.js
 @ ./src/components sync \.story\.js$
 @ ./.storybook/config.js
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./.storybook/config.js ./node_modules/webpack-hot-middleware/client.js?reload=true

Question / Issue

Does this loader work with Webpack v5?

I added it but the mixins and sass variables are not found once webpack bundles it.

Is there a way I can debug the output and whether something is happening during the transpilation?

必须在template 里面加上style标签且内容不为空,才会加载样式

// button component

  <button class="btn">
    <slot>{{text}}</slot>
  </button>
</template>
<script>
export default {
  name: 'Button',
  props: {
    text: {
      type: String,
      default: 'button',
    },
  },
};
</script>
<style lang="stylus" scoped>
// required
</style>

// vue.config.js

pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'stylus',
      patterns: [
        path.resolve(__dirname, './src/styles/index.styl'),
      ],
    },
  },

// index.styl

@import './palette.styl'
@import './common.styl'
@import './default.styl'
@import './layout.styl'
@import './components'
@import './mobile.styl'

打算用style-resources-loader来预加载所有的style(不只variable/mixins,其他组建样式也一起加载), 发现要在template 里面加上style标签 且必须有内容预加载的样式才会显示。
这是是否为预期的结果,可以用来加载全部样式吗

<style lang="stylus" scoped>
// required
</style>

Compilation error from loader whenever there are @use rules in .scss files

Whenever I have an @use rule inside a .scss file, I get this error on compilation:

Error: @use rules must be written before any other rules.

My guess here is that the style-resources-loader is either:

  • a) Using @import rules to prepend my files with the automatic imports I defined. Or:
  • b) It's injecting the content of those files after my @use imports.

Either a) or b) would result in the error I'm seeing.

So, is it possible to configure the loader to use @use instead of @import to prepend my files with the .scss imports I specified? Or, alternatively, can I configure the loader to 'hoist' my @use rules so that the automatically injected content is placed only below them?

Thank you in advance for any help.

vue-cli2.x中导入less变量文件失败

你好,项目有点旧了,用的vue-cli2.x搭建,预处理器用的less,想为组件全局导入变量、mixin资源。

这里是 build/utils.js 内loaders的配置文件代码:配置文件代码;是按照说明文档中的example去配置的....

但是启动项目在组件内使用全局变量less文件内的变量,还是没有识别。

求告知阿~另外在网上搜索这个问题,出现最多的还是推荐使用sass-resources-loader,是推广不够吗hhhhhh

import路径的计算似乎有些没有覆盖的场景

假设我们的结构是这样的:

/src <-- context
  /styles
    variables.less <-- pattern
  /components
    /FooBar
      /index.less <-- use
/node_modules
  /reset-less
    index.less

/src作为context,将/src/styles/variables.less作为被style-resources-loader处理的文件。在variables.less中写这样的代码:

@import "reset-less/index.less";

此时这个@import语句会被loader的逻辑修改为:../node_modules/reset-less/index.less

这导致在/src/components/FooBar/index.less中多出了@import "../node_modules/reset-less/index.less";这样一条语句,显然这是不可能找到正确的文件的

It doesn't work in webpack 5

In webpack 5, the resource will not inject to other style file. Both sass and less, if I try to inject a variable to style file, webpack will throw a error variable is not defined.

Import PostCSS .css files

I have mixins, custom-media, and other PostCSS-only features that I'd like to store in a .css file and import them into my components using style-resources-loader, but it appears this only works with LESS, SCSS, SASS, and Stylus.

Would it be possible to point it directly to a .css file that contained some PostCSS extended features?

Something like:

patterns: [
     path.resolve(__dirname, 'path/to/postcss/mixins/*.css'),
     path.resolve(__dirname, 'path/to/postcss/custommedia/*.css')
],

?

Vue.js with mocha and styles-resources-loader can't load dependency sass

I have the problem that mochapack does not seem to work together with the style resources loader.

packages that seem to produce the problem:

  • "@vue/cli-plugin-unit-mocha": "~4.2.0",
  • "vue-cli-plugin-style-resources-loader": "~0.1.4"

My vue.config.js file:

const path = require("path");

module.exports = {
  ...

  pluginOptions: {
    "style-resources-loader": {
      preProcessor: "scss",
      patterns: [path.resolve(__dirname, "./src/assets/styles/*.scss")]
    }
  }
};

The single sass file that is included through the above config:

@import "~vue-select/src/scss/vue-select.scss";

It seems to load the vue-select.scss correctly but then when interpreting this file it seems to loose its current directory and does not find the imported style.

Error log excerpt:

Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Can't find stylesheet to import.
  ╷
1 │ @import "global/variables";
  │         ^^^^^^^^^^^^^^^^^^
  ╵
  /node_modules/vue-select/src/scss/vue-select.scss 1:9  @import
  /src/components/HelloWorld.vue 1:9 

See full detail error message and code:
https://github.com/petritz/food-calculator-web/runs/560575367

Very serious performance issues

The style-resources-loader solved less Variable undefined problem well.
But When I add several path in the patterns . I use 8092 MB to run npm run build,it throw Maximum still call stack size exceeded .

最新的vue-cli中使用官方推荐的vue.config.js配置 实际不生效

vue.config.js 配置如下

// vue.config.js
const path = require('path')

module.exports = {
  chainWebpack: config => {
    const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
    types.forEach(type => addStyleResource(config.module.rule('stylus').oneOf(type)))
  },
}

function addStyleResource (rule) {
  rule.use('style-resource')
    .loader('style-resources-loader')
    .options({
      patterns: [
        path.resolve(__dirname, './src/public.styl'),
      ],
    })
}

Add webpack 5 support

This loader is completely compatible with webpack 5, however npm 7 requires peer dependencies to match exactly, please publish a version allowing webpack 5 as peer dependency

"main" in package.json is wrong since 1.4.0

The latest update to version 1.4.0 breaks the package because main in package.json points to lib/index.js which is not present. Since 1.4.0 the lib folder has a subfolder src and this is where the index.js file now lies.

Filter where not to inject

I want to not inject the styles in some files, is it possible?
Right now I have created my custom injector and if the sources includes a special text, for example `/* not inject*/ I'm not injecting there, but could be nice if I can send an array of filenames.

Individual injector to each pattern?

Hello! Plugin is awesome! One question: It's possible to make works individual injector to each pattern?
I have a components library, and i want to make this works: http://s3.micp.ru/BPVBj.jpg
In this short example file named as btn.scss don't know variables defined in btn.config.scss, same as file btn.override.scss don't know map variables, defined in btn.config.scss;

I don't want to do internal imports in scss files, because this slows down the rebuild of the project, and also makes it impossible to import a new file without access to the file itself. I want to make sure that every component in the components folder, for example btn, is recognized by the loader by the mask. I think that this idea would make it work similarly to imports in scss.

Thanks for any reply!

Parse error?

Hello, could you pls explain smth for me?
I have a stylus mixin in mixins.styl file and it's the reason why my custom webpack bundle throw a parse error
I don't really understand what's the problem because my another bundle (on gulp though) doesn't have such problem

Here's the mixin

`

   textSizing($fsS,$lhS,$fsE,$lhE,$wS,$wE)
         font-size: unit($fsS, 'px')
         line-height: unit($lhS, 'px')
        @media screen and (max-width: unit($wS, 'px')) // - line which causes trouble with parcer
	    $gDiff = '(100vw - %s)' % unit($wE, 'px');
	    $wDiff = ($wS - $wE);
	     $fsDiff = ($fsS - $fsE);
	     $lhDiff = ($lhS - $lhE);
	     $fsF = s('calc(%s / %s  * %s + %s)',$gDiff, $wDiff, $fsDiff, unit($fsE, 'px'))
	     $lhF = s('calc(%s / %s  * %s + %s)',$gDiff, $wDiff, $lhDiff, unit($lhE, 'px'))

	    font-size: $fsF
	    line-height: $lhF 

`

Here's how it made in config
`

{
loader: 'style-resources-loader',
options: {
patterns: [
path.resolve(__dirname, './src/styles/variables.styl'),
path.resolve(__dirname, './src/styles/mixins.styl'),
path.resolve(__dirname, './src/styles/optimize.styl'),
path.resolve(__dirname, './src/styles/global.styl'),
path.resolve(__dirname, './src/views/header/header.styl'),
path.resolve(__dirname, './src/views/footer/footer.styl'),
path.resolve(__dirname, './src/styles/libs/*.styl'),
],
injector: (source, resources) => {
const combineAll = type => resources
.filter(({ file }) => file.includes(type))
.map(({ content }) => content)
.join('');

            return combineAll('variables') + combineAll('mixins') + combineAll('optimize') + combineAll('global') + combineAll('header') + combineAll('footer') + source;
        }
      }
    }

`

Failed to cache .less files on Win 10 with Webpack 4

We used SRL with Webpack 3, and it worked well both on Windows and Ubuntu. After we upgraded Webpack from 3 to 4, there is a significant improvement for incremental build speed on Ubuntu. But for windows, this is not the case. It took ~30s for every incremental build on windows. Through examining the Webpack log and some simple tests, we found that SRL caused .less files to rebuild on every incremental build. Here is the minimal reproducible repo with two branches, one use SRL, and one use @import to load the baseStyle.less file.

After some debugging, we found that SRL uses glob to match the patterns option and returns Unix style file path like D:/you/path/to/less/file.less. It then adds this Unix style file path to the dependency list of the current module. While the needRebuild method which controls the cache behavior of Webpack uses windows style file path on windows.

TheneedRebuild method has two parameters: fileTimestamps and contextTimestamps, which both are filePath -> timestamps Map. The keys of these two Maps are windows style file path like D:\\you\\path\\to\\less\\file.less, and the values are timestamps when the corresponding file was updated.

Due to the mismatch of these two file path styles, the needRebuild method returns false every time and thus .less files rebuild on every incremental build.

No variables being loaded

I have my Webpack set up to use your plugin, and the Antd LESS files are included successfully, but my (test) custom variables are not being injected. This is the pertinent part of my webpack.base.js:

{
        test: /\.less$/,
        use: ['style-loader', 'css-loader', 'less-loader', {
          loader: 'style-resources-loader',
          options: {
            patterns: path.join(__dirname, '../../app/*.less'),
            injector: (source, resources) => source + resources.map(({ content }) => content).join(''),
          },
        }],
      },

Are there any steps I can take to fix this, or figure out the source of the issue?

打包后的css文件会出现重复样式,好像是加载的组件都被打包一次

image
image

这是我的 vue.config.js 配置

const path = require('path')
const CompressionWebpackPlugin = require('compression-webpack-plugin')

function resolve (dir) {
  return path.join(__dirname, dir)
}

module.exports = {
  productionSourceMap: false,
  chainWebpack: config => {
    config.plugins.delete('prefetch')

    config.optimization.minimize(true)

    config.entry.app = ['@babel/polyfill', 'src/main.js']
  },
  configureWebpack: () => ({
    plugins: [
      new CompressionWebpackPlugin({
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.css$|\.ttf$|\.html$|\.svg$|\.json$|\.js$/,
        threshold: 0, // 只有大小大于该值的资源会被处理
        minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
        deleteOriginalAssets: false // 删除原文件
      })
    ]
  }),
  css: {
    // 是否使用css分离插件 ExtractTextPlugin
    extract: true,
    // 开启 CSS source maps?
    sourceMap: false,
    // css预设器配置项
    loaderOptions: {},
    // 启用 CSS modules for all css / pre-processor files.
    modules: false
  },
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [
        resolve('src/assets/common/param.less'),
        resolve('src/assets/common/common.less')
      ]
    }
  }
}

Fail to import google fonts with sass

// FILE: vue.config.js
const path = require("path")

module.exports = {
  pluginOptions: {
    ...
    'style-resources-loader': {
      preProcessor: 'sass',
      patterns: [
        path.resolve(__dirname, 'src/assets/styles/main.sass')
      ]
    }
    ...
  }
}
// FILE: main.sass
@import url('https://fonts.googleapis.com/css?family=Karla:400,700|Rubik:400,500,700')

Error:

File to import not found or unreadable: ../assets/styles/url('https://fonts.googleapis.co│
m/css?family=Karla:400,700|Rubik:400,500,700')

mixin和variables会输出到style标签内,而且有很多重复项(一个组件产生一个style)

// vue.config.js
rules: [
{
test: /.(css|less)$/,
use: [
{
loader: 'style-resources-loader',
options: {
patterns: [
path.resolve(__dirname, './node_modules/@souche-ui/lemon/less/global.less'),
path.resolve(__dirname, './src/assets/style/mixin.less')

                            ]
                        }
                    }
                ]
            }
        ]

// mixin.less
.flex-between() {
display: flex;
justify-content: space-between;
align-items: center;
}

image
不想让这些mixin或者变量文件被输出到style标签内

How do I set in CRA with craco?

I want to auto import less variables in all files, but fails. Here are my settings:

// craco.config.js
module.export = {
  plugins: [
    {
       plugin: styleResourcesLoader,
       options: {
         patterns: path.resolve(__dirname, './src/styles/variables.less')
       }
    }
  ]
}

It doesn't work! How can I fix it? Thanks!!!!

Support of modules with @ sign

Hello,

Thank you for this helpful library! The only issue i have is, that the regular expression for the require statement should also match paths with @ sign in module names. This is quite common in current libraries and unfortunately our own packages within our monorepo are prefixed with @.

For me, the statement should look like this:
const requireReg = /require\s*\((["'])([\w.\/@]+)(?:\1)\)((?:\.[\w_-]+)*);?/igm;

Best Regards
Stefan

请问在引入了全局less之后如何开启vscode的变量提示?谢谢

通过这种方式引入了全局变量,然后在开发时候不会提示。

  chainWebpack: (config) => {
    config.module
      .rule('less')
      .oneOfs.values()
      .forEach((item) => {
        item
          .use('style-resources-loader')
          .loader('style-resources-loader')
          .options({ patterns: './src/themes/variable.less' })
          .end();
      });
  }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.