Giter Site home page Giter Site logo

postcss-easy-import's Introduction

postcss-easy-import Build Status

PostCSS plugin to inline @import rules content with extra features.

Usage

postcss([ require('postcss-easy-import') ])

See PostCSS docs for examples for your environment.

Resolving files with globs

The path to the file will be checked and if it contains a glob it will be used to locate it. These can be mixed and matched with normal module paths:

@import "suitcss-utils-display"; /* node_modules */
@import "./theme.css"; /* relative path */
@import "./components/*.css"; /* glob */
@import "suitcss-utils-size/lib/*.css"; /* glob inside node_modules */

Options

This plugin is a postcss-import extension which introduces its own resolve option.

prefix

Type: false or string Default: false

Allows partial-like importing with a prefix before the filename.

@import 'modules/partial.css';
/* will import modules/_partial.css */

Prefixed versions are always favoured. Otherwise the non-prefix version is used:

├── _baz.css
├── baz.css
├── bar.css

The matched files would be ['_baz.css', 'bar.css'].

extensions

Type: array or string Default: .css

Defines file extensions which will be looked for.

License

MIT © Bogdan Chadkin

postcss-easy-import's People

Contributors

knynkwl avatar lmoval avatar marzelin avatar simonsmith avatar trysound 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

postcss-easy-import's Issues

Compatibility with PostCSS 8

Thanks for your PostCSS plugin!

As you probably know, PostCSS 8 was released a few days ago. It would be great if you could make this plugin compatible with the latest version. The creators of the project have even released this migration guide.

Unstable glob import

Globbing will throw an error when a file contains syntax errors, whereas a regular import does not.

Steps to reproduce:

  1. Create a PostCSS with a syntax error, say, color #333; (this example is missing a semicolon)
  2. Import the file via @import './path/to/file';

This is working without throwing any errors for me.

Change the import to be:

@import '/path/**/*';

It should error with:

[21:58:59] Plumber found unhandled error:
 Error in plugin 'gulp-postcss'
Message:
    ENOENT: no such file or directory, open '/Users/jmeas/WebDev/moolah/client-src/meta/components/**/*.css'
Details:
    errno: -2
    code: ENOENT
    syscall: open
    path: /Users/jmeas/WebDev/moolah/client-src/meta/components/**/*.css
    fileName: /Users/jmeas/WebDev/moolah/client-src/css/index.css
Stack:
Error: ENOENT: no such file or directory, open '/Users/jmeas/WebDev/moolah/client-src/meta/components/**/*.css'
    at Error (native)

Correcting the syntax error allows for the glob to work.

I'm OK with syntax errors erroring, but I'd expect the error to relate to syntax errors, rather then ENOENT (which isn't true!)


I am using gulp for this, but I figure the error is likely here. Lmk if you think otherwise and I'll check out the postcss gulp plugin.

Not able to import without extension and when file contains comments

So far my postcss.config.js file looks like this:

module.exports = ({ file, options, env }) => ({
  plugins: [
    require('postcss-easy-import'),
    require('postcss-url'),
    require('postcss-preset-env')({
      browsers: 'last 4 versions',
      stage: 0,
    }),
    require('postcss-strip-inline-comments'),
    require('postcss-sassy-mixins'),
    require('postcss-simple-vars'),
    require('postcss-nested'),
    require('pixrem')(),
    require('autoprefixer')({
      browsers: ['last 4 versions'],
    }),
    env === 'production' ? require('cssnano') : null,
  ],
});

and my webpack.config.js includes these parts:

 const MiniCssExtractPlugin = require("mini-css-extract-plugin");

...

module: {
    rules: [{
      test: /\.scss$/,
      use: [MiniCssExtractPlugin.loader, {
        loader: 'css-loader',
        options: {
          importLoaders: 1,
          modules: true,
          sourceMap: true,
          localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
        },
      }, 'postcss-loader'],
    }],
  },
...
plugins: [
...
    new MiniCssExtractPlugin({
      filename: "style.css",
      chunkFilename: "[id].css"
    }),
  ],

the webpack build breaks always whenever:

  • I try to import into the .scss file loaded using css modules a file without specifying the full name, so to import a file named _settings.scss I cannot use settings.scss or _settings
  • whatever .scss file contains a comment starting with //; I get SyntaxError (1:1) Unknown word
  • If I want to import a file from a module e.g. Bootstrap mixins file it cannot resolve @import "bootstrap/scss/_mixins.scss"; as it returns the error Module not found: Error: Can't resolve './bootstrap/scss/_mixins.scss', I need to specify the full relative path @import "../../node_modules/bootstrap/scss/_mixins.scss";

Cannot get glob modules to work

A very simple testcase is @import asm.css/lib/align-self/*.css; where asm.css is a node_module, it seems easy import isn't resolving it for some reason?

Relevant files

postcss.config.js (using postcss-cli)

module.exports = (ctx) => ({
  'no-map': true,
  plugins: {
    'postcss-easy-import': {},
    'postcss-reporter': {}
  }
})

building:
./node_modules/.bin/postcss $file -o $ofile
where $file is
@import "asm.css/lib/align-self/*.css";
of which asm.css/lib/align-self/* exists and has files in node_modules

Import error message does not specify error file's path

Using sugarss, when trying to import a file with an error (in this case, adding a semicolon at the end of a line), with the following project structure:

styles/styles.sss (master file)
styles/utils/mixins.sss

postcss-import outputs the full path of the nested error with the error type:
postcss-import: /Users/.../utils/mixins.sss:17:42: Unnecessary semicolon,
postcss-easy-import only outputs precss: /Users/.../styles.sss:9:1: Could not resolve the @import for "utils/mixins.sss".

Is it not possible to keep the full path in order to know what should be fixed and where?

Compatibility with .pcss

Using PostCSS and before was just using as extensions .css.
So for example having something like this works:

@import "vars.css";
@import "fonts.css";
@import "all.css";
@import "main.css";
@import "../../components/**/*.css";

I'm now in the process of changing the extensions of the stylesheet files to .pcss and the plugins seems not to work.

@import "vars.pcss";
@import "fonts.pcss";
@import "all.pcss";
@import "main.pcss";
@import "../../components/**/*.pcss";

All the files get correctly imported apart from the one inside components subfolders.

Any idea why and/or what to do to try to fix this issue?

Expected behavior, or not?

If I use this plugin like so:

.pipe($.postcss([
    precss({import: {prefix: ''}}),
    easyImport({extensions: ['.sss']})
  ], {parser: sugarss}))

should I expect

@import 'my-file' to resolve to my-file.sss? It's only working if I do @import 'my-file.sss'. If I omit the extension, I get this error:

Message:
    ENOENT: no such file or directory, open '/Users/jmeas/WebDev/moolah/client-src/css/my-file.css'
Details:
    errno: -2
    code: ENOENT
    syscall: open
    path: /Users/jmeas/WebDev/moolah/client-src/css/my-file.css
    fileName: /Users/jmeas/WebDev/moolah/client-src/css/index.sss
Stack:
Error: ENOENT: no such file or directory, open '/Users/jmeas/WebDev/moolah/client-src/css/my-file.css'
    at Error (native)

If I turn off this plugin, PostCSS works exactly the same. Am I misconfiguring this, or something? 😕

Make prefix optional

With prefix: "_" declared I'd like the import to be able to import either test.scss or _test.scss with a preference to the prefixed one if both are found.

Node module import issues with Webpack 4 + SCSS

I'm finding node_module import a bit hit and miss with my main SCSS import in Webpack + MiniCssExtract. Some seem to work, some don't. For example...

@import "animate.css"; -> this import works perfectly and loads the animate.css module. Note the .css is there because that's the name of the actual node module.

However, @import "lity"; does not work and I receive this error below. Looks like the problem is it trying to use the .js file instead of the css?

Invalid CSS after "...Licensed MIT */": expected selector, was "(function(window, f"
          in C:\websites\wpdev\wp-content\themes\gutendev\node_modules\lity\dist\lity.js (line 4, column 1)

So for that module I have to put in the full path like so to import the file:
@import "/node_modules/lity/dist/lity.css";

Allow both module lookup and glob imports at same time

Hi @TrySound , thanks for your great plugin!
I have a question about the opportunity of a new feature. Do you think would it be possibile to extend @import resolution and make it accept both module lookup and glob imports at same time?

In my case I have a project where I'd like to import some CSS with a standard modules @import tree and some others CSS picking the files up with a **/*.css globbing style into a specific folder.

Any advice would be greatly appreciated.

Andrea

feature request: import into selector

Given a file some.css containing

a {color: red}

It would be most useful to be able to do

.foo {
   @import `some.css`;
}

and get

.foo a {
    color: red
}

This isn't behaviour it's easy to simulate in any other way afaict

[Motivation:

Image your app has multiple themes. you put your styles in a file which uses variables and do

.theme-red {
  --colour: red;
  @import `some.css`;
}

.theme-green {
  --colour: green;
  @import `some.css`;
}

]

Nested @import rules and relative module resolution

See tailwindlabs/tailwindcss#428

I'm trying to do this:

@responsive {
  @import 'suitcss-components-grid';
}

However, when it tries to resolve, it always looks locally:

ERROR in ./node_modules/css-loader??ref--2-1!./node_modules/postcss-loader/lib??ref--2-2!./src/css/index.scss
Module not found: Error: Can't resolve './suitcss-components-grid' in '/Users/timkelty/Sites/dlr-craft3/src/css'
resolve './suitcss-components-grid' in '/Users/timkelty/Sites/dlr-craft3/src/css'
  using description file: /Users/timkelty/Sites/dlr-craft3/package.json (relative path: ./src/css)

I'm thinking this is because of this behavior from postcss-import:

Note: nested @import will additionally benefit of the relative dirname of imported files.

Any ideas?

Problem when used with broccoli-postcss-single in Ember 3.5+

This is probably not a problem with postcss-easy-import itself, but I wanted to get your insights, so here goes:

I'm using postcss-easy-import to import css files from the node_module folder, which used to work flawlessly.

After updating our project to the latest version of Ember cli (3.7) things stopped working. I think might be related to Ember cli > 3.5 upgrading to broccoli 2 which uses the system temporary folder when building. PostCSS now throws a warning with the message that it can't find the files that are stored in the node_modules folder.

The weird thing is that if I use postcss-import directly the files are found. So while the problem is probably caused by broccoli, I still think that something can be done in the postcss-easy-import module resolver.

Any idea what resolve-module.js is doing differently than postcss-import's to make it not find the files?

More technical details: I'm using an addon called ember-cli-postcss which uses broccoli-postcss-single under the hood.

node_modules resolve not working with @import for SCSS

I'm running into this error msg when I'm trying to @import a .scss file from my node_modules folder via this method:

@import "react-input-range/src/scss/index.scss";

Results in this error:

[!] (postcss plugin) Error: File to import not found or unreadable: react-input-range/src/scss/index.scss.

However, if I include the entire relative path to the .scss, that'll work:

@import "../../../../../../node_modules/react-input-range/src/scss/index.scss";

and this works as well

@import "react-input-range/lib/css/index.css";

I need to import the .scss to override the SASS variables, so can't make use of of the .css file. I can't seem to figure out the cause and need some assistance with my issue, thanks!


So to reiterate:

Component.scss

// Works
@import "react-input-range/lib/css/index.css"; 
@import "../../../../../../node_modules/react-input-range/src/scss/index.scss";

// Does not work
@import "react-input-range/src/scss/index.scss";

rollup.config.js

import easyImport from "postcss-easy-import";
import postcssFlexbugsFixes from 'postcss-flexbugs-fixes';
import autoprefixer from "autoprefixer";

postcss({
    sourceMap: true,
    minimize: true,
    modules: true,
    namedExports: true,
    plugins: [
        easyImport,
        postcssFlexbugsFixes,
        autoprefixer({
            browsers: [
                '>1%',
                'last 4 versions',
                'Firefox ESR',
                'not ie < 9', // React doesn't support IE8 anyway
            ],
            flexbox: 'no-2009',
        }),
    ],
    extract: path.resolve("./dist/style.css"),
}),

Getting postcss-easy-import to work with Webpack's alias resolve module directive

Hi --

I'm working on a web app project that is making use of Webpack v3 and postcss. Webpack is configured to use the postcss-loader and postcss is configured to use the postcss-easy-import plugin. The problem I'm running into is that postcss-easy-import doesn't work with webpack's alias resolve directive (https://webpack.js.org/configuration/resolve/#resolve-alias).

My web app project's directory structure is setup like so:

/src
    /app
        /modules
            /core
            /theme
            /featureA
            /featureB

In the webpack config, we setup a resolve mapping so that each child directory under src/app/modules/ is aliased against app-[module]. So, for instance, app-core would resolve to src/app/modules/core. (The justification for this is so that we don't have to deal with relative paths and it makes splitting the app's modules up into separate node modules easier when we partition the logic.) Aliases work fine for JavaScript files using babel, but when using the @import directive within a CSS file that references another CSS in a module that aliases to one of the app's module folders, things fail. For example, if I have a CSS file named theme.css in the directory src/app/modules/featureA:

// theme.css
@import 'app-theme/colors.css';

This will cause webpack to output an error saying the module app-theme/colors.css could not be resolved from the /projects/web-app/src/app/modules/featureA.

Digging into the postcss-easy-import code, I see that the module's resolve-module logic only resolves against node_modules and web_modules using the resolve npm module (https://github.com/TrySound/postcss-easy-import/blob/master/lib/resolve-module.js#L15). If the logic could be updated such that some kind of optional hook/middleware/plugin could be provided to dynamically check against other module directories, that, I think, would help solve the problem I'm running into. An optional hook would allow postcss-easy-import to then work with different tools that have their own module resolving logic. This would also assure that the postcss-loader does not need to get involved to help support postcss-easy-import resolve aliased modules, which it shouldn't have to do.

Anyway, I wanted to raise the problem here to see if this all makes sense and that I'm not overlooking something important. Thoughts?

Resolving webpack aliases

Hi,

I cannot resolve scss file with webpack alias. is it a normal behavior ?

I get this error :

WARNING in .//css-loader?{"sourceMap":true,"modules":true,"localIdentName":"[name][local][hash:base64:3]","minimize":false}!.//postcss-loader!./components/UserPage/styles.scss
postcss-import: /Users/toto/web/components/UserPage/styles.scss:1:1: Cannot find module 'scss/main.scss' from '/Users/toto/web/components/UserPage'

styles.css contains :
@import "scss/main.scss
and below is the function I use in my webpack config:

  postcss(bundler) {
    return {
      plugins: [
        require('postcss-easy-import')({
          addDependencyTo: bundler,
          // path: path.resolve(__dirname, 'assets/scss'),
        }),
        require('autoprefixer')(),
      ],
      syntax,
      parser: syntax,
    };

Unclear how to setup imports

I'm not completely sure how to do this right.

I've got a script that uses sugarss to outpout a .css file from an .sss file. So after installing postcss-reasy-import (npm i -D postcss-easy-import), running postCSS using sugarCSS I get the following:

/src/css/main.sss
/src/css/main.css  - what postcss outputted after running my postcss using sugarass npm script.

Trying to now figure out how to use postcss-easy-import to import my .css file that sugarss generated into my inde.html:

index.html


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    @import "./src/css/main.css"

...

I think I need to specify an extension? It says it defaults t css...so if I'm using sugarss but I'm trying to import a css file I assume I don't need to specify an extension since I'm importing a css file! right?

When I run this though I get the literal value @import "./src/css/main.css" printed to the page when I load my index.html page.

So stuck here.

~ prefix support

IDEA (Webstorm) supports prefix ~ by default. So support of this prefix would be nice.
image
image

Is it possible to control sorting of hyphenated filenames?

Before we started using postcss-easy-import, stylesheets were included manually, like so:

@import "./components/input.css";
@import "./components/input-extra.css";
@import "./components/input-group.css";

Now that we are using postcss-easy-import we don't have to do that, we can do:

@import "./components/*";

The problem is that it seems to be importing stylesheets without hyphenation last. So the above will actually end up being equivalent to:

@import "./components/input-extra.css";
@import "./components/input-group.css";
@import "./components/input.css";

Might there anyway to control the sort order? Ideally some sort of natural sort would take into effect. Thanks for your time!

PostCSS easy import with Next.js

I am using PostCSS http://cssnext.io/ with my Next.js website combined with butterCMS. I am new to postcss but like what they are trying to do, however coming from a SASS background, I am finding it seems to be going down the rabbit hole of having to add a lot of additional modules and scripts in order to get it working which does not give it a major advantage over preprocessors.

In my package.json I have the following modules:

"postcss-cssnext": "^3.0.2",
"postcss-easy-import": "^3.0.0",
"postcss-loader": "^2.0.6",
"postcss-modules": "^0.8.0",

In my root I have a ./styles/ folder with the following files:

defaults.css

:root {
  /* Breakpoints */
  @custom-media --small (width >= 576px);
  @custom-media --medium (width >= 768px);
  @custom-media --large (width >= 1200px);

  /* Colors */
  --color-black: #000;
  --color-white: #fff;
  --color-vue-green: #42b983;

  /* Typography */
  --h1: 2rem;
  --h2: 1.5rem;
  --h3: 1.25rem;
  --h4: 1rem;
  --h5: 0.875rem;
  --h6: 0.75rem;

  /* Utilities */
  --accessibly-hidden: {
    position: absolute !important;
    display: block;
    visibility: visible;
    overflow: hidden;
    width: 1px;
    height: 1px;
    margin: -1px;
    border: 0;
    padding: 0;
    clip: rect(0, 0, 0, 0);
    clip-path: polygon(0 0, 0 0, 0 0, 0 0);
  }

    --foo: {

      font-size:4em;
      color:green;}

}

styles.css

@import 'defaults.css';

h1, h2, h3, h4, h5, h6 {
  font-weight: normal;
}

h1 { font-size: var(--h1) }
h2 { font-size: var(--h2) }
h3 { font-size: var(--h3) }
h4 { font-size: var(--h4) }
h5 { font-size: var(--h5) }
h6 { font-size: var(--h6) }

.accessibly-hidden {
  @apply --accessibly-hidden;
}

.giantext{
  @apply --foo;
}


div {
  color: var(--color-vue-green);
}

.my-paragraph{
  composes: my-paragraph from 'shared.css';
}

.danger{
  composes: danger from 'shared.css';
}

In my react script I have:

<p className={classNames['my-paragraph']}>My homepage</p>
<p className={classNames.danger}> This background should be yellow</p>
<div>
  <p className={classNames.giantext}> I am huge </p>
</div>

The remainder gives me the following warnings/errors:

(Emitted value instead of an instance of Error) postcss-custom-properties: /Users/user/projects/qubase/styles/styles.css:25:3: variable '--color-vue-green' is undefined and used without a fallback

Or

(Emitted value instead of an instance of Error) postcss-apply: /Users/user/projects/qubase/styles.css:16:3: No custom property set declared for `accessibly-hidden`.

etc

Only the composes directives are working with the remaining utilities and styling not being picked up by my index.js file. However if I add the contents of defaults.css directly into styles.css the styling works which meakes me think that the import directive is not working. Is there anything I am missing here?

Resolve glob imports

I have following files:
src/my.css

@import "vars.css";
* {
    color: $my-color;
}

src/vars.css

$my-color: red;

and index.css

@import './src/*.css';

When I run postcss index.css I get following result:

* {
    color: $my-color;
}

$my-color: red;

If I change the name of vars.css file to something like avars.css (which comes before my.css alphabetically) or if I use specific path in index.css instead of glob everything works as expected and the result is:

$my-color: red;

* {
    color: $my-color;
}

I think it is a bug and dependencies resolution shouldn't be broken by using globs.

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.