yenshih / style-resources-loader Goto Github PK
View Code? Open in Web Editor NEWCSS processor resources loader for webpack
License: MIT License
CSS processor resources loader for webpack
License: MIT License
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:
@import
rules to prepend my files with the automatic imports I defined. Or:@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.
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
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
有tag方便查看每个版本的代码,这样看起来不是很方便
这是我的 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')
]
}
}
}
Hi! Great loader!
I added it to nuxt.js: nuxt/nuxt#2172
Could you add a Stylus?
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!!!!
In CSS, only POSIX path (../../foo
) is allowed. But on Windows, Windows path (..\..\foo
) is inserted in CSS, and so resolving import url fails.
假设我们的结构是这样的:
/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";
这样一条语句,显然这是不可能找到正确的文件的
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.
SyntaxError: Invalid regular expression: /@(?:import|require)\s+(?:\([a-z,\s]+\)\s*)?['"]?(?<pathToResource>[^'"\s;]+)['"]?;?/: Invalid group
Which is introduced by c5fa232.
(?<pathToResource>
(named capture groups) is supported from Node.js 10.3, see: https://node.green/
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-cli2.x搭建,预处理器用的less,想为组件全局导入变量、mixin资源。
这里是 build/utils.js 内loaders的配置文件代码:配置文件代码;是按照说明文档中的example去配置的....
但是启动项目在组件内使用全局变量less文件内的变量,还是没有识别。
求告知阿~另外在网上搜索这个问题,出现最多的还是推荐使用sass-resources-loader,是推广不够吗hhhhhh
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.
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
.
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?
// 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')
我是引入了antd的样式,然后用作者这个插件把antd的样式import进来,进行变量覆盖、提取和公用的,但是这样引入后打包变的巨慢。
I have the problem that mochapack does not seem to work together with the style resources loader.
packages that seem to produce the problem:
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
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
Maybe you could ask the folks at ant-design to suggest style-resources-loader
here: https://ant.design/docs/react/customize-theme
They link to an article which uses modifyVars
... but your loader is way better since the changes can be picked up by webpack without a restart of the dev-server.
Feel free to close this thank you note 👍
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'),
],
})
}
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.
今早上来,此包突然不行了,看了下作者是升级了两个版本1.4.0和1.4.1,但是我的package.json里面是写的"style-resources-loader": "^1.3.3",为啥会自动去找最新的呢
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;
}
}
}
`
// 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>
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?
// 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;
}
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!
通过这种方式引入了全局变量,然后在开发时候不会提示。
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();
});
}
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
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.