GithubHelp home page GithubHelp logo

intoli / antd-scss-theme-plugin Goto Github PK

View Code? Open in Web Editor NEW
201.0 8.0 83.0 1.69 MB

A Webpack plugin for customizing Ant Design with an SCSS theme file and using Ant Design's compiled variables in SCSS files throughout your project.

Home Page: https://intoli.com/blog/antd-scss-theme-plugin/

License: Other

JavaScript 96.80% CSS 1.94% HTML 1.26%
antd scss-theme webpack-setup webpack-plugin stylesheets

antd-scss-theme-plugin's Introduction

antd-scss-theme-plugin Tweet Share on Facebook Share on Reddit Share on Hacker News

Build Status License NPM Version

antd-scss-theme-plugin is a Webpack plugin which allows you to effectively use Ant Design in a project with SCSS styling. With it you can:

  1. Customize Ant Design by specifying theme variable overrides through a single theme.scss file.
  2. @import Ant Design's theme and color variables from your theme.scss file.
  3. Hot reload your project when theme.scss changes.

๐Ÿ“– For a more detailed overview of the plugin and its usage, check out the Using Ant Design in Sass-Styled Projects article on Intoli's blog.

Table of Contents

Installation

This plugin is published as antd-scss-theme-plugin on npm:

npm install --save-dev antd-scss-theme-plugin

It extends the functionality of a antd, less-loader and sass-loader to accomplish its goals. These are listed as peerDependencies in package.json, and you can install them with:

npm install --save antd
npm install --save-dev less-loader sass-loader

Configuration

To use antd-scss-theme-plugin, you need to configure Ant Design to use Less stylesheets when loading components, and to connect a few loaders with the plugin in your Webpack setup. You can find a fully configured project in the example directory.

Step 1. Configure Ant Design to Use Less Stylesheets

In order to customize Ant Design's theme, you need to configure antd to load its components with Less stylesheets instead of with pre-compiled CSS. The official documentation explains this to some degree, but here are the explicit steps you should take.

  1. Install babel-plugin-import, a package published by the makers of antd.

  2. Modify the plugin section of your Babel setup to use this package with antd:

    "plugins": [
      ["import", {
        "libraryName": "antd",
        "style": true
      }]
    ]

    The "style": true option is what enables the use of Less components.

  3. Configure less-loader to compile antd components. This can be done by adding something like the following to your Webpack config's loaders array:

    {
      test: /\.less$/,
      use: [
        {
          loader: 'style-loader',
          options: {
            sourceMap: process.env.NODE_ENV !== 'production',
          },
        },
        {
          loader: 'css-loader',
          options: {
            importLoaders: 1,
            sourceMap: process.env.NODE_ENV !== 'production',
          },
        },
        'less-loader',
      ],
    }

    Obviously, this also requires you to install style-loader and css-loader.

With that setup, you can import self-contained antd components with lines like following:

import { Button } from 'antd';

So, in addition to enabling styling customizations, this has the potential to reduce the size of your Webpack bundle.

Step 2. Use antd-scss-theme-plugin in Your Webpack Setup

First, initialize the plugin by passing your theme file's path to the plugin's constructor, and add the plugin to your Webpack config's plugins array:

import AntdScssThemePlugin from 'antd-scss-theme-plugin';

const webpackConfig =  {
  // ...
  plugins: [
    new AntdScssThemePlugin('./theme.scss'),
  ],
};

Second, wrap your less-loader and sass-loader Webpack configs with AntdScssThemeFile.themify(). For example, in the config from Step 1, you would change the line

'less-loader',

to

AntdScssThemePlugin.themify('less-loader'),

This works even when your loader has options, e.g., you would change

{
  loader: 'sass-loader',
  options: {
    sourceMap: process.env.NODE_ENV !== 'production',
  },
}

to

AntdScssThemePlugin.themify({
  loader: 'sass-loader',
  options: {
    sourceMap: process.env.NODE_ENV !== 'production',
  },
})

Usage

Customize Ant Design's Theme

With the project configured, you can customize Ant Design's theme by specifying Ant Design theme variables in your SCSS theme file (e.g., theme.scss). For example, if theme.scss has the following contents

/* theme.scss */
$primary-color: #fe8019;

then the interface will no longer be based off of the default blue #1890ff, but rather a louder orange #fe8019:

Effects of Changing Primary Color to #fe8019

You can customize any Less variable that antd uses in this way: just relace @ with a $, e.g., @info-color becomes $info-color.

Use Ant Design's Customized Color and Theme Variables

Importing theme.scss in some SCSS file gives it access all of Ant Design's theme and color variables. This is true even if you specify only a subset of the available theme variables in theme.scss. For instance, with theme.scss containing only a $primary-color definition as above, you would still be able to do something like:

@import '../theme.scss';

.header {
  color: $blue-10; /* From colors.less */
  padding: $padding-lg; /* From themes/default.less */
}

Live Reload Components when Ant Design Styles Change

Since antd-scss-theme-plugin registers your theme file as a watched dependency with Webpack, changes in the theme file will result in recompilations of components that use it. To learn how to set up your project to use live reloading, see the working example.

antd-scss-theme-plugin's People

Contributors

jleechatnels avatar prncc avatar sangaline avatar vieira 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  avatar  avatar  avatar  avatar

antd-scss-theme-plugin's Issues

Fails to compile

Ejected create react app with --scripts-version=react-scripts-ts. Followed the tutorials and scss files seem to compile nicely until I try to modify the variables, in which case it fails to build with

Undefined variable: "$primary-9". in blah\App.scss

Webpack plugin -
new AntdThemePlugin(path.join(__dirname, "src", "theme.scss"))

scss files -

/* theme.scss */
@import "~antd/dist/antd.css";
$primary-color: #cc241d;

/* App.scss
* -------------------
*/
@import "./theme.scss";

.App {
  text-align: center;
  color: $primary-9;
}

Webpack loaders -

{
  test: /\.scss$/,
  use: [
    "style-loader",
    {
      loader: require.resolve("css-loader"),
      options: {
        importLoaders: 1,
        modules: true,
        camelCase: true
      }
    },
    AntdThemePlugin.themify("sass-loader")
  ]
},
{
  test: /\.less$/,
  use: [
    "style-loader",
    {
      loader: require.resolve("css-loader"),
      options: {
        importLoaders: 1
      }
    },
    AntdThemePlugin.themify("less-loader")
  ]
},
{
  test: /\.css$/,
  use: [
    require.resolve("style-loader"),
    {
      loader: require.resolve("css-loader"),
      options: {
        importLoaders: 1
      }
    },
    {
      loader: require.resolve("postcss-loader"),
      options: {
        // Necessary for external CSS imports to work
        // https://github.com/facebookincubator/create-react-app/issues/2677
        ident: "postcss",
        plugins: () => [
          require("postcss-flexbugs-fixes"),
          autoprefixer({
            browsers: [
              ">1%",
              "last 4 versions",
              "Firefox ESR",
              "not ie < 9" // React doesn't support IE8 anyway
            ],
            flexbox: "no-2009"
          })
        ]
      }
    }
  ]
},

Issues when running tests with Jest

Hi and thanks for a nice plugin!

I have some issues when trying to setup jest with my project. To confirm my issues i cloned your example, installed jest and created a test:

import App from '../App';

describe('App', () => {
    it('should render the app', () => {});
});

Notice that I don't even use the App in my test, but only by importing the component (which contains some antd imports) it causes this error:

` FAIL src/components/tests/App.test.js
โ— Test suite failed to run

/Users/andree/Documents/Hobby/antd-scss-theme-plugin/example/node_modules/antd/lib/style/index.less:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){@import "./themes/default";
                                                                                         ^

SyntaxError: Invalid or unexpected token

  29 |     </FormItem>
  30 |
> 31 |     <FormItem
     | ^
  32 |       label="Enable"
  33 |       labelCol={{ span: 8 }}
  34 |       wrapperCol={{ span: 8 }}

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.<anonymous> (node_modules/antd/lib/button/style/index.js:3:1)
  at Object.<anonymous> (src/components/App.jsx:31:1)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.249s
Ran all test suites.
error Command failed with exit code 1.`

Do you have any idea what's going on?

If I uncomment the App import in my test, the test completes (duuh :D)

Thanks!

This plugin reduces webpack packaging speed

Before add this plugin my webpack bundle duration is 5000ms ๏ผŒafter add this plugin my webpack bundle duration is 9000-10000ms .
How can I increase the speed,after add this plugin.

Undefined variable: "$secondary-color".

The project is init using create-react-app, and eject to expose webpack config.

In webpack.config.dev rules, I add the following loaders (less and sass)

       {
            test: /\.s[ac]ss$/,
            use: [
              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                },
              },

              AntdScssThemePlugin.themify('sass-loader'),
            ],
          },
          {
            test: /\.less$/,
            use: [
              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                },
              },

              AntdScssThemePlugin.themify({
                loader: 'less-loader',
                options: { javascriptEnabled: true },
              }),
            ],
          },

In the plugin section, I add

new AntdScssThemePlugin('src/common/theme.scss'),

===========

I create the following files;

src/common/theme.scss

$primary-color: #fe8019;
src/index.scss

@import './common/theme.scss';

.test {
  color: $secondary-color;
}

Then I got the error ,

Module build failed: 
  color: $secondary-color;
        ^
      Undefined variable: "$secondary-color".
      in /Users/michael/dev/jtech-web/src/index.scss (line 4, column 10)

Based on the docs,
Importing theme.scss in some SCSS file gives it access all of Ant Design's theme and color variables.

So am I missing something?

Compile takes a long time

Hi,

I have been using this plugin for a couple of years. Initially, it worked well since we had fewer SCSS files. But when the project got bigger and SCSS files increase so the compiler started taking time to compile the code in development environment.

antd-sass-theme-plugin reduces the build time.

when i use this plugin it reduces the build time. it takes around 4 seconds to finish the scss build.
my project has just started and it takes around 4 seconds to build just the scss files.
initially i thought it was because sass-loader is slow. but with the new speed-measure-webpack-plugin it pointed out the actual cause of the slow performance.

here is the plugin output for the speed

General output time took 5.42 secs

 SMP  โฑ  Plugins
HtmlWebpackPlugin took 0.196 secs
NamedModulesPlugin took 0.012 secs
ProgressPlugin took 0.004 secs
HotModuleReplacementPlugin took 0.004 secs
MiniCssExtractPlugin took 0.003 secs
NoEmitOnErrorsPlugin took 0.002 secs
AntdScssThemePlugin took 0 secs
DefinePlugin took 0 secs
LoaderOptionsPlugin took 0 secs
SystemBellPlugin took 0 secs

 SMP  โฑ  Loaders
css-loader, and
postcss-loader, and
antd-scss-theme-plugin took 4.07 secs
  module count = 7
babel-loader, and
eslint-loader took 0.302 secs
  module count = 1

here you can check the module count as well.

**webpack config **

        {
          test: /\.css$/,
          use: [
            !isProd ? 'style-loader' : MiniCssExtractPlugin.loader,
            {
              loader: 'css-loader',
              options: {
                include: path.resolve(__dirname, '../', './src'),
                sourceMap: false,
              },
            },
            {
              loader: 'postcss-loader',
              options: {
                sourceMap: false,
                include: path.resolve(__dirname, '../', './src'),
                plugins() {
                  return [autoprefixer('last 2 versions', 'ie 10')];
                },
              },
            },
          ],
        },
        {
          test: /\.scss$/,
          use: [
            !isProd ? 'style-loader' : MiniCssExtractPlugin.loader,
            {
              loader: 'css-loader',
              options: {
                sourceMap: false,
                include: path.resolve(__dirname, '../', './src'),
              },
            },
            {
              loader: 'postcss-loader',
              options: {
                sourceMap: false,
                include: path.resolve(__dirname, '../', './src'),
                plugins() {
                  return [autoprefixer('last 2 versions', 'ie 10')];
                },
              },
            },
            AntdScssThemePlugin.themify({
              loader: 'fast-sass-loader',
              options: {
                processCssUrls: false,
                sourceMap: false,
                include: path.resolve(__dirname, '../', './src'),
                data: '@import "~Styles/themes/core";@import "~Styles/themes/anttheme";',
              },
            }),
          ],
        },
        // extra loader only because of antd designs
        {
          test: /\.less$/,
          use: [
            !isProd ? 'style-loader' : MiniCssExtractPlugin.loader,
            {
              loader: 'css-loader',
              options: {
                sourceMap: false,
                include: path.resolve(__dirname, '../', './src'),
              },
            },
            {
              loader: 'postcss-loader',
              options: {
                sourceMap: false,
                include: path.resolve(__dirname, '../', './src'),
                plugins() {
                  return [autoprefixer('last 2 versions', 'ie 10')];
                },
              },
            },
            AntdScssThemePlugin.themify({
              loader: 'less-loader',
              options: {
                include: path.resolve(__dirname, '../', './src'),
                sourceMap: false,
              },
            }),
          ],
        },

**common plugins **

    new webpack.ProgressPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new SystemBellPlugin(),
    new MiniCssExtractPlugin({
      filename: 'css/[name].css',
      allChunks: true,
    }),
    new AntdScssThemePlugin('./src/Styles/themes/anttheme.scss'),
  ],

*ignore the config how its written , i have devided my config into multiple files feature wise. *

the point here is does it really takes 4 seconds to build a simple 7 module project or i am doing something wrong.

| NODE | 9.6.1 |
|NPM | 6.2.0 |
|webpack | 4.16.2|
|antd | 3.7.1 |
|antd-scss-theme-plugin | 1.0.6 |

Could not compile the SCSS theme file error.

No matter what I try I can't get around this. I am trying to implement the plugin with gatsbyjs and am very close, the only problem now is that I am running into the following error:

Could not compile the SCSS theme file "src/lib/ant-overrides.scss" for the purpose of variable extraction. This is likely because it contains a Sass error.

My relevant project directory looks like this:

plugins/
  gatsby-plugin-sass-antd/
    gatsby-node.js
src/
  lib/
      ant-override.scss

So I am assuming this might have to do with gatsby's custom config and I am running into a compatibility problem with the setup. Basically I am extending and modifying the webpack config within gatsby-node.js. The less-loader addition is working fine, but it wasn't until I added the reference to the custom scss file that the build started breaking.

Here is the relevant code within gatsby-node:

plugins: [
  new AntdScssThemePlugin('./src/lib/ant-overrides.scss'),
]

And the ant-overrides.scss

$primary-color: #000;

Is there something I am missing?

Parcel

Amazing project! Is there any chance (long shot, I know) that you might look at implementing this plugin for Parcel bundler as well?

Thanks in advance!

plugin not compatible with ng-zorro-antd.

I installed ng-zorro-antd && antd-scss-theme-plugin in angular project. Post installation and plugin configuration, it started throwing errors. themeEntryPath issues.
I changed the path

const themeEntryPath = require.resolve('ng-zorro-antd/style/themes/default.less');

after that i changed the sass-loader plugin to version ^7.0.0 because loader API Schema was not compatible. (not compatible with sass-loader ^8.0.0).

Now it is throwing

Invalid CSS after " */": expected 1 selector or at-rule, was "import 'core-js/pro"

can this plugin be made compatible with ng-zorro-antd?

This version has been deprecated

This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial)

plase update this package

$icon-url block compile

I set $icon-url in theme.scss and it make webpack compile error

image

compile success without this variable.

Does this variable support to less?

Import of another scss is not working

Hello!

I am trying to import another scss file with partials into theme.scss. It seems this is not supported?

Use case: There are multiple websites under the same brand. They share same logo, fonts and so on. However, parameters like website colors can vary from site to site, since they have different content

I would like to have a theme file with same basics: fonts, sizes, line heights and so on, which differ from standard

I want to be able to extend this theme with other colors and some other parameters.

This plugin returns me this errors for import at the moment:

Could not compile the SCSS theme file "./theme.scss" for the purpose of variable extraction. This is likely because it contains a Sass error.

Error: Invalid CSS after "...test { content:": expected expression (e.g. 1px, bold), was '@import "../src/bas'\n on line 1 of stdin\n>> .test { content: @import "../src/base-theme.scss" }

theme.scss:

@import "../src/base-theme.scss";
$primary-color: yellow;

Is there some workaround for it?

Usage outside antd

Hi there just found this awesome plugin when trying to solve runtime theming with antd.

If I have libraries which use antd components, and follow the same theming solution as antd (the library components can be passed in babel-plugin-import to have its less files loaded in compilation), can the library also be themed using this? Or is this hardcoded to only work for antd components?

I want to provide my library consumer with the same theming ability provided by using this plugin, if possible.

theme.scss won't let me use @font-face

For example, adding this to my theme.scss won't let it compile due to a generic "SASS error". Any help is appreciated.

@font-face { font-family: 'BC Sans'; src: url('../assets/fonts/BCSans-Regular.woff'); }

The error:

Module build failed (from ./node_modules/antd-scss-theme-plugin/build/dist/lib/antdLessLoader.js):
Could not compile the SCSS theme file "C:\Users\Luke\source\repos\bcgov\mds\services\minespace-web\src\styles\settings\theme.scss" for the purpose of variable extraction. This is likely because it contains a Sass error.

Accept optionless loaders

themify should handle 'less-loader' (and similar) in addition to

{
  loader: 'less-loader,
  options: {}
}

Major release checks

Use of ^ in dependencies locks major version. This means the following are outdated.

What's the strategy to manage this?

npm-check

babel-eslint                      ๐Ÿ˜Ž  MAJOR UP  Major update available. https://github.com/babel/babel-eslint
                                               npm install --save-dev [email protected] to go from 8.2.6 to 10.0.3

babel-loader                      ๐Ÿ˜Ž  MAJOR UP  Major update available. https://github.com/babel/babel-loader
                                               npm install --save-dev [email protected] to go from 7.1.5 to 8.0.6

babel-plugin-add-module-exports   ๐Ÿ˜Ž  MAJOR UP  Major update available. https://github.com/59naga/babel-plugin-add-module-exports#readme
                                               npm install --save-dev [email protected] to go from 0.2.1 to 1.0.2

cross-env                         ๐Ÿ˜Ž  MAJOR UP  Major update available. https://github.com/kentcdodds/cross-env#readme
                                               npm install --save-dev [email protected] to go from 5.2.1 to 6.0.3

eslint                            ๐Ÿ˜Ž  MAJOR UP  Major update available. https://eslint.org
                                               npm install --save-dev [email protected] to go from 4.19.1 to 6.6.0

eslint-config-airbnb              ๐Ÿ˜Ž  MAJOR UP  Major update available. https://github.com/airbnb/javascript
                                               npm install --save-dev [email protected] to go from 16.1.0 to 18.0.1

eslint-loader                     ๐Ÿ˜Ž  MAJOR UP  Major update available. https://github.com/webpack-contrib/eslint-loader
                                               npm install --save-dev [email protected] to go from 1.9.0 to 3.0.2

less-loader                       ๐Ÿ˜Ž  MAJOR UP  Major update available. https://github.com/webpack-contrib/less-loader
                                               npm install --save-dev [email protected] to go from 4.1.0 to 5.0.0

raw-loader                        ๐Ÿ˜Ž  MAJOR UP  Major update available. https://github.com/webpack-contrib/raw-loader
                                               npm install --save-dev [email protected] to go from 0.5.1 to 3.1.0
                                  ๐Ÿ˜•  NOTUSED?  Still using raw-loader?
                                               Depcheck did not find code similar to require('raw-loader') or import from 'raw-loader'.
                                               Check your code before removing as depcheck isn't able to foresee all ways dependencies can be used.
                                               Use --skip-unused to skip this check.
                                               To remove this package: npm uninstall --save-dev raw-loader

rimraf                            ๐Ÿ˜Ž  MAJOR UP  Major update available. https://github.com/isaacs/rimraf#readme
                                               npm install --save-dev [email protected] to go from 2.7.1 to 3.0.0

sass-loader                       ๐Ÿ˜Ž  MAJOR UP  Major update available. https://github.com/webpack-contrib/sass-loader
                                               npm install --save-dev [email protected] to go from 7.3.1 to 8.0.0

webpack                           ๐Ÿ˜Ž  MAJOR UP  Major update available. https://github.com/webpack/webpack
                                               npm install --save-dev [email protected] to go from 3.12.0 to 4.41.2

Use with react-app-rewired

I'm trying to use the plugin with 'react-app-rewired' and I have succeeded to use it to customize the theme, but if I import theme.scss and try to use Ant Design's variables I get 'Undefined variable' errors (I can only use the ones I have defined in the file).

Here is my config-overrides.js file:

const { getLoader, injectBabelPlugin } = require('react-app-rewired');
const rewireSass = require('react-app-rewire-scss');
const rewireLess = require('react-app-rewire-less');
const rewireEslint = require('react-app-rewire-eslint');
const AntdScssThemePlugin = require('antd-scss-theme-plugin');

module.exports = function override(config, env) {
  // use babel-plugin-import to import antd components
  config = injectBabelPlugin(
    [
      'import',
      {
        libraryName: 'antd',
        style: true
      }
    ],
    config
  );

  // add scss support
  config = rewireSass(config, env);

  // add less support to antd
  config = rewireLess.withLoaderOptions({
    javascriptEnabled: true
  })(config, env);

  // override eslint config
  config = rewireEslint(config, env);

  // inject plugin to overrride antd theme with sass
  config = injectBabelPlugin(new AntdScssThemePlugin('./theme.scss'), config);

  // override the sass and less loaders to use the ones from AntdScssThemePlugin
  themify(config, '.scss', 'sass-loader');
  themify(config, '.less', 'less-loader');

  return config;
};

// override a loader with the one from AntdScssThemePlugin
function themify(config, ext, loaderName) {
  const rule = getLoader(
    config.module.rules,
    rule => rule.test && rule.test.test(ext)
  );

  const loader =
    rule && rule.use && rule.use.find(item => item.loader === loaderName);

  if (loader) {
    Object.assign(loader, AntdScssThemePlugin.themify(loader));
  }
}

Less variables not being imported

I've been working to get Antd running in Next.js with SCSS with cssModules. I have been able to get it all running except for getting the Antd Less variables. I can overwrite the Less variables from my 'theme.scss' file, but when I import that file, I can't get access to the Less variables as expected. I get errors complaining of a Sass error because a variable doesn't exist.

Any idea when this plugin will get some TLC? Lots of outdated deps...

Compatibility issue with sass-loader, Error: Sass Loader has been initialised using an options object that does not match the API schema. - options has an unknown property 'importer'.

The version 1.0.8 (latest) of antd-scss-theme-plugin is not compatible with sass-loader(8.0.0) latest. It shows the following error:

Invalid options object. Sass Loader has been initialised using an options object that does not match the API schema. options has an unknown property 'importer'. These properties are valid: object { implementation?, sassOptions?, prependData?, sourceMap?, webpackImporter? }

moderate severity vulnerabilities in 'hoek' package

There are 4 moderate vulnerabilities after installing this plugin

Moderate Prototype pollution

Package hoek

Patched in > 4.2.0 < 5.0.0 || >= 5.0.3

Dependency of antd-scss-theme-plugin [dev]

Path antd-scss-theme-plugin > less > request > hawk > boom > hoek

More info https://nodesecurity.io/advisories/566

Moderate Prototype pollution

Package hoek

Patched in > 4.2.0 < 5.0.0 || >= 5.0.3

Dependency of antd-scss-theme-plugin [dev]

Path antd-scss-theme-plugin > less > request > hawk > cryptiles >
boom > hoek

More info https://nodesecurity.io/advisories/566

Moderate Prototype pollution

Package hoek

Patched in > 4.2.0 < 5.0.0 || >= 5.0.3

Dependency of antd-scss-theme-plugin [dev]

Path antd-scss-theme-plugin > less > request > hawk > hoek

More info https://nodesecurity.io/advisories/566

Moderate Prototype pollution

Package hoek

Patched in > 4.2.0 < 5.0.0 || >= 5.0.3

Dependency of antd-scss-theme-plugin [dev]

Path antd-scss-theme-plugin > less > request > hawk > sntp > hoek

More info https://nodesecurity.io/advisories/566

found 4 moderate severity vulnerabilities in 16528 scanned packages
4 vulnerabilities require manual review. See the full report for details.


Can you fix it? Thanks!

Resolve absolute paths

Hello,

I have been using your plugin with sass-loader and node-sass.

node-sass has an option which allows us to specify the root folder of absolute @import paths:

{
  test: /\.scss$/i,
  loader: 'sass-loader',
  options: {
    includePaths: [
      './src/',
    ],
  },
}

includePaths is an option of node-sass and sass-loader just passes it through when compiling.

The problem is, this plugin doesn't look for this path when resolving the current imported file to decide whether or not to include the antd theme variables in src/antdSassLoader.js at line 22. It simply uses the resolver of sass-loader, not node-sass. This means that importing my antd theme file using an absolute path (e.g. @import 'style/theme.scss';) does not expose the antd theme variables.

The workaround is simply to use a relative path when importing this specific file when the antd variables are needed, but this is tedious.

Do you think adding an option to allow custom root folder, or an option to specify a resolver function overriding sass-loader's importsToResolve() would be viable for this plugin?

My best guess would be to simply consider this behaviour non standard and never use absolute paths on @import.

Maintenance?

Hi guys, thanks for your work!!!

Seems like the project is kind of abandoned or maybe you don't have enough time to take care of the issues.

  • Are you accepting PR?
  • Would you recommend to contribute or rather fork the project and provide the necessary changes?

A suggestion and a word of caution re: build performance

I commented here: #43 on what I thought was a bug with this library.

However it wasn't a bug with this library at all. I, as a naive developer confused by webpack took this plugin literally and applied the AntdScssThemePlugin.themify() changes to my rule which matched all my scss files. This caused this entire theme to rebuild on every scss file change (incremental build) adding ~10seconds and also slowed down the initial build by ~10s. This seems to be intended, as I think it makes possible the features here: https://github.com/intoli/antd-scss-theme-plugin#use-ant-designs-customized-color-and-theme-variables however we don't use it in this way, and we have alot of scss files.

If my understanding is correct, many users would benefit from avoiding wrapping all their scss loaders with this library. In this case I think an update to the README with the expected build speed savings would be prudent, which I would be happy to contribute to

Could not compile the SCSS theme file error - post create-react-app eject

Hello,

I ejected from CRA in order to configure web-pack to hook up the webpack config settings to override the default sass-loader and less-loaders provided.

My webpack config looks like this:

My directory is something like:

config
...
webpack.config.dev.js
src
theme.scss

my .babelrc is

{    
    "presets": [
    "react-app"
    ]
    ,
    "plugins" : [
    ["import", {
      "libraryName": "antd",
      "style": true
    }]
  ]
}

and my webpack.config.dev.js looks like this:


rules: [
      // less loading config
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'style-loader',
            options: {
              sourceMap: !isProduction,
            },
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              sourceMap: !isProduction,
              modules: true,
              camelCase: true,
              localIdentName: '[name]-[local]-[hash:base64:5]',
            },
          },
          AntdScssThemePlugin.themify({
            loader: 'sass-loader',
            options: {
              sourceMap: !isProduction,
            },
          }),
        ],
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: 'style-loader',
            options: {
              sourceMap: !isProduction,
            },
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              sourceMap: !isProduction,
            },
          },
          AntdScssThemePlugin.themify('less-loader'),
        ],
      },

and:

  plugins: [
    // AntdScss theming plugin
    new AntdScssThemePlugin(path.join(__dirname, 'src', 'theme.scss')),

Here's my theme.scss file:

$primary-color: #cc241d;

Any help would be appreciated, thanks!

Vue CLI 3 Example

Not sure where to start trying to get this to work with vue CLI 3.0 -- But I'm poking around and will update here if I do. Anyone else done this?

scss compile error

If you use antd variable in theme.scss file without specifying it first, compilation fails with scss error.

theme.scss file

$input-border-color:$primary-color;

Fails because $primary-color is not defined.

I tried it in your example and got the same error.

TypeError: compilation.fileDependencies.includes is not a function

Got this error

node_modules/antd-scss-theme-plugin/build/dist/lib/index.js:21
      if (compilation.fileDependencies && !compilation.fileDependencies.includes(theme)) {
                                                                        ^
TypeError: compilation.fileDependencies.includes is not a function

Ran it with debugger on, it showed me compilation.fileDependencies is not an array but a Set.

My workaround:

export class AntdScssTheme extends AntdScssThemePlugin {

    apply(compiler) {
        const afterEmit = (compilation, callback) => {
            // Watch the theme file for changes.
            const theme = AntdScssThemePlugin.SCSS_THEME_PATH;
            if ( compilation.fileDependencies && ! compilation.fileDependencies.has(theme) ) { // modified
                compilation.fileDependencies.add(theme); // modified
            }
            callback();
        };

        // Register the callback for...
        if ( compiler.hooks ) {
            // ... webpack 4, or...
            const plugin = { name: 'AntdScssThemePlugin' };
            compiler.hooks.afterEmit.tapAsync(plugin, afterEmit);
        } else {
            // ... webpack 3.
            compiler.plugin('after-emit', afterEmit);
        }
    }
}

readme error

image
Maybe it should be AntdScssThemePlugin.themify('less-loader') not AntdScssThemePlugin('less-loader') ๐Ÿ˜„

Problem with PROD build with react-app-rewired

Hi everyone,

With the following config-overrides.js, I can run the application in dev mode no problem. However, when I make a prod build (npm run build) the theme overrides don't happen. There are no errors. Help.

const path = require('path');
const { compose, getLoader, injectBabelPlugin } = require('react-app-rewired');
const rewireSass = require('react-app-rewire-scss');
const rewireLess = require('react-app-rewire-less');
const AntdScssThemePlugin = require('antd-scss-theme-plugin');

function addAliases(config, env) {
  return {
    ...config,
    resolve: {
      alias: {
        assets: path.resolve(__dirname, 'src/assets/'),
        theme: path.resolve(__dirname, 'src/theme/')
      }
    }
  };
}

function addStyling (config, env) {
  // use babel-plugin-import to import antd components
  config = injectBabelPlugin(
    ['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }],
    config
  );

  // add scss support
  config = rewireSass.withLoaderOptions({
    includePaths: [path.resolve(__dirname, 'src/theme/')]
  })(config, env);

  // add less support to antd
  config = rewireLess.withLoaderOptions({
    javascriptEnabled: true,
    importLoaders: 1
  })(config, env);


  // inject plugin to overrride antd theme with sass
  config.plugins = [
    ...config.plugins,
    new AntdScssThemePlugin(path.resolve(__dirname, 'src/theme/_theme.scss'))
  ]

  // override the sass and less loaders to use the ones from AntdScssThemePlugin
  themify(config, '.scss', 'sass-loader');
  themify(config, '.less', 'less-loader');

  return config;
};

// override a loader with the one from AntdScssThemePlugin
function themify(config, ext, loaderName) {
  const rule = getLoader(
    config.module.rules,
    rule => rule.test && rule.test.test(ext)
  );

  const loader =
    rule && rule.use && rule.use.find(item => item.loader === loaderName);

  if (loader) {
    Object.assign(loader, AntdScssThemePlugin.themify(loader));
  }
}

module.exports = compose(
  addAliases,
  addStyling,
);

Plz Fix Warnings

warning antd-scss-theme-plugin > less > request > [email protected]: This module moved to @hapi/hawk. Please make sure to switch over as this distribution is no longer supported and may contain bugs and critical security issues.
warning antd-scss-theme-plugin > less > request > hawk > [email protected]: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
warning antd-scss-theme-plugin > less > request > hawk > [email protected]: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
warning antd-scss-theme-plugin > less > request > hawk > [email protected]: This module moved to @hapi/sntp. Please make sure to switch over as this distribution is no longer supported and may contain bugs and critical security issues.
warning antd-scss-theme-plugin > less > request > hawk > sntp > [email protected]: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
warning antd-scss-theme-plugin > less > request > hawk > [email protected]: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
warning antd-scss-theme-plugin > less > request > hawk > cryptiles > [email protected]: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
warning antd-scss-theme-plugin > less > request > hawk > boom > [email protected]: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).

Do we really need this package if we use create-react-app and react-app-rewired? (Trying to understand) (Working code below)

My current project is currently in Ant.d, Less, Create-react-app and uses react-app-rewired, customize-cra for custom webpack configurations.

File: ./src/antdCustom.scss
---------------------------
$btn-primary-bg: #616161;
$color: black;

Current config-override.js looks like this, and it works perfectly. Please tell me why I need this package?

File: ./config-overrides.js
-------------------------
const {adjustWorkbox, fixBabelImports, addLessLoader, override, adjustStyleLoaders, addWebpackPlugin } = require('customize-cra');
const fs = require('fs');
const _ = require('lodash');
const  scssToJson = require('scss-to-json');

const scssThemeVariables = scssToJson('./src/antdCustom.scss');
const lessThemeVariables = _.mapKeys(scssThemeVariables, (value, key) => key.replace(/^\$/, '@'));

console.log(lessThemeVariables)

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),
  addLessLoader({
    lessOptions:{
      javascriptEnabled: true,
      modifyVars: lessThemeVariables
    }
  })
);

Still trying to understand why I need this package? Please, help!

Plugin doesn't work with sass-loader v8 and above and less-loader v6 and above

Spend hours trying to get the plugin to work. Seems like sass-loader and less-loader both changed their options object shapes. I got to the bottom of the issue by exploring antdSassLoader.js and antdLEssLoader.js.

  1. antdSassLoader.js (the error was something like options has an unknown property 'importer')
    The issue there is that there is no importer prop in options anymore, it's in sassOptions. So should be something like this:
newOptions.sassOptions = {}
newOptions.sassOptions.importer = importer
  1. antdLEssLoader.js (the error was something like options has an unknown property 'modifyVars')
    The issue here is that modifyVars was moved inside lessOptions prop and you also must pass javascriptEnabled: true (without is the error you're getting is (Inline JavaScript is not enabled. Is it set in your options?) to lessOptions like this:
  const newOptions = _extends({}, options, {
    lessOptions: {
      modifyVars: _extends({}, themeModifyVars, options.modifyVars || {}), 
      javascriptEnabled: true
    }
  });

Without those changes, you're getting a bunch of different errors.

Screenshots of "successful" configs are attached.

Screen Shot 2020-07-28 at 12 20 33 AM

Screen Shot 2020-07-28 at 12 19 57 AM

Could not compile the SCSS theme file "../scss/app.scss" for the purpose of variable extraction

Hi, i have been trying to setup my project using this plugin. However the Plugin not working for me and keeps throwing error " Could not compile the SCSS theme file "../scss/app.scss" for the purpose of variable extraction. This is likely because it contains a Sass error "

Webpack version: 4.41
sass-loader: 8
less-loader: 5
antd-scss-theme-plugin: "^1.0.8"

ERROR in ./node_modules/antd/es/style/index.less (./node_modules/css-loader/dist/cjs.js??ref--4-1!./node_modules/antd-scss-theme-plugin/build/dist/lib/antdLessLoader.js??ref--4-2!./node_modules/antd/es/style/index.less)
    Module build failed (from ./node_modules/antd-scss-theme-plugin/build/dist/lib/antdLessLoader.js):
   Could not compile the SCSS theme file "../scss/app.scss" for the purpose of variable extraction. This is likely because it contains a Sass error.
    @ ./node_modules/antd/es/style/index.less 1:14-156 20:4-31:5 23:25-167
   @ ./node_modules/antd/es/button/style/index.js
    @ ./src/pages/Home/index.js
     @ ./src/App.js
    @ ./src/index.js
  @ multi ./src/index.js webpack-hot-middleware/client

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.