Giter Club home page Giter Club logo

postcss-import's Introduction

postcss-import

Build Version postcss compatibility

PostCSS plugin to transform @import rules by inlining content.

This plugin can consume local files, node modules or web_modules. To resolve path of an @import rule, it can look into root directory (by default process.cwd()), web_modules, node_modules or local modules. When importing a module, it will look for index.css or file referenced in package.json in the style or main fields. You can also provide manually multiples paths where to look at.

Notes:

  • This plugin should probably be used as the first plugin of your list. This way, other plugins will work on the AST as if there were only a single file to process, and will probably work as you can expect.
  • Running postcss-url after postcss-import in your plugin chain will allow you to adjust assets url() (or even inline them) after inlining imported files.
  • In order to optimize output, this plugin will only import a file once on a given scope (root, media query...). Tests are made from the path & the content of imported files (using a hash table). If this behavior is not what you want, look at skipDuplicates option
  • If you are looking for Glob Imports, you can use postcss-import-ext-glob to extend postcss-import.
  • If you want to import remote sources, you can use postcss-import-url with its dataUrls plugin option to extend postcss-import.
  • Imports which are not modified (by options.filter or because they are remote imports) are moved to the top of the output.
  • This plugin attempts to follow the CSS @import spec; @import statements must precede all other statements (besides @charset).

Installation

$ npm install -D postcss-import

Usage

Unless your stylesheet is in the same place where you run postcss (process.cwd()), you will need to use from option to make relative imports work.

// dependencies
const fs = require("fs")
const postcss = require("postcss")
const atImport = require("postcss-import")

// css to be processed
const css = fs.readFileSync("css/input.css", "utf8")

// process css
postcss()
  .use(atImport())
  .process(css, {
    // `from` option is needed here
    from: "css/input.css"
  })
  .then((result) => {
    const output = result.css

    console.log(output)
  })

css/input.css:

/* remote urls are preserved */
@import "https://example.com/styles.css";

/* can consume `node_modules`, `web_modules` or local modules */
@import "cssrecipes-defaults"; /* == @import "../node_modules/cssrecipes-defaults/index.css"; */
@import "normalize.css"; /* == @import "../node_modules/normalize.css/normalize.css"; */

@import "foo.css"; /* relative to css/ according to `from` option above */

/* all standard notations of the "url" value are supported */
@import url(foo-1.css);
@import url("foo-2.css");

@import "bar.css" (min-width: 25em);

@import 'baz.css' layer(baz-layer);

body {
  background: black;
}

will give you:

@import "https://example.com/styles.css";

/* ... content of ../node_modules/cssrecipes-defaults/index.css */
/* ... content of ../node_modules/normalize.css/normalize.css */

/* ... content of css/foo.css */

/* ... content of css/foo-1.css */
/* ... content of css/foo-2.css */

@media (min-width: 25em) {
/* ... content of css/bar.css */
}

@layer baz-layer {
/* ... content of css/baz.css */
}

body {
  background: black;
}

Checkout the tests for more examples.

Options

filter

Type: Function
Default: () => true

Only transform imports for which the test function returns true. Imports for which the test function returns false will be left as is. The function gets the path to import as an argument and should return a boolean.

root

Type: String
Default: process.cwd() or dirname of the postcss from

Define the root where to resolve path (eg: place where node_modules are). Should not be used that much.
Note: nested @import will additionally benefit of the relative dirname of imported files.

path

Type: String|Array
Default: []

A string or an array of paths in where to look for files.

plugins

Type: Array
Default: undefined

An array of plugins to be applied on each imported files.

resolve

Type: Function
Default: null

You can provide a custom path resolver with this option. This function gets (id, basedir, importOptions, astNode) arguments and should return a path, an array of paths or a promise resolving to the path(s). If you do not return an absolute path, your path will be resolved to an absolute path using the default resolver. You can use resolve for this.

load

Type: Function
Default: null

You can overwrite the default loading way by setting this option. This function gets (filename, importOptions) arguments and returns content or promised content.

skipDuplicates

Type: Boolean
Default: true

By default, similar files (based on the same content) are being skipped. It's to optimize output and skip similar files like normalize.css for example. If this behavior is not what you want, just set this option to false to disable it.

addModulesDirectories

Type: Array
Default: []

An array of folder names to add to Node's resolver. Values will be appended to the default resolve directories: ["node_modules", "web_modules"].

This option is only for adding additional directories to default resolver. If you provide your own resolver via the resolve configuration option above, then this value will be ignored.

warnOnEmpty

Type: Boolean
Default: true

By default postcss-import warns when an empty file is imported.
Set this option to false to disable this warning.

Example with some options

const postcss = require("postcss")
const atImport = require("postcss-import")

postcss()
  .use(atImport({
    path: ["src/css"],
  }))
  .process(cssString)
  .then((result) => {
    const { css } = result
  })

dependency Message Support

postcss-import adds a message to result.messages for each @import. Messages are in the following format:

{
  type: 'dependency',
  file: absoluteFilePath,
  parent: fileContainingTheImport
}

This is mainly for use by postcss runners that implement file watching.


CONTRIBUTING

  • โ‡„ Pull requests and โ˜… Stars are always welcome.
  • For bugs and feature requests, please create an issue.
  • Pull requests must be accompanied by passing automated tests ($ npm test).

postcss-import's People

Contributors

0xcaff avatar borodean avatar greenkeeper[bot] avatar guybedford avatar iamvdo avatar jednano avatar jonathantneal avatar kswedberg avatar lexich avatar magsout avatar marzelin avatar meomix avatar moox avatar mstade avatar nodaguti avatar oleersoy avatar oscarotero avatar r-browser-app-team avatar realityking avatar renovate[bot] avatar romainmenke avatar ryanzim avatar simonsmith avatar snuggs avatar swernerx avatar thomheymann avatar trysound avatar wommy avatar zerocho avatar zoubin 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

postcss-import's Issues

onImport has wrong file paths

It looks to me like the first arg of the onImport callback is the file that's doing the importing and every subsequent arg is a file that it imports. Is that correct? If so, it's definitely not working properly. I have 3 files:

/* global.css */
@import foo;
/* page1.css */
@import foo;
@import bar;
/* page2.css */
@import bar;
@import foo;

With the following configuration:

require('postcss-import')({
    path: 'styles/blocks',
    onImport: function(files) {
        console.log('========== import ==========');
        files.forEach(function(file) {
            gutil.log('import:', file);
        });
    }
}),

And here's what I get in the shell:

13:53 $gulp styles
[13:54:12] Using gulpfile z:\gulpfile.js
[13:54:12] Starting 'styles'...
[13:54:12] Finished 'styles' after 37 ms
========== import ===========
[13:54:12] import: z:\styles\sheets\global\global.css
[13:54:12] import: z:\styles\blocks\block-foo.css
========== import ===========
[13:54:12] import: z:\styles\sheets\global\global.css
[13:54:12] import: z:\styles\blocks\block-foo.css
[13:54:12] import: z:\styles\blocks\block-bar.css
========== import ===========
[13:54:12] import: z:\styles\sheets\global\global.css
[13:54:12] import: z:\styles\blocks\block-bar.css
[13:54:12] import: z:\styles\blocks\block-foo.css

Notice how global.css is mentioned 3 times here, when it should have mentioned page1.css and page2.css.

Any ideas?

also resolve in web_modules

web_modules are like node_modules, but local.
webpack support (created?) it.
I "just" need to add it into the resolved dir & (and add tests)

File containing same content shouldn't be skipped

Currently, if a file contains the same content as another, it's skipped. This can fail in cases like this:

/* main.css */
@import "foo/index.css";
@import "bar/index.css";
/* both foo/index.css and bar/index.css has this content  */
@import "baz/index.css";

This causes bar/baz/index.css not being imported.

postcss-import does not work with postcss 4.0

I get the following error:

/Users/nullstyle/src/tmp/busted/node_modules/postcss-import/node_modules/postcss-message-helpers/index.js:79
    throw err
          ^
TypeError: <css input>:1:1: Cannot call method 'map' of undefined
    at <css input>:1:1
    at Root.Container.normalize (/Users/nullstyle/src/tmp/busted/node_modules/postcss/lib/container.js:451:25)
    at Root.normalize (/Users/nullstyle/src/tmp/busted/node_modules/postcss/lib/root.js:44:45)
    at Root.Container.insertBefore (/Users/nullstyle/src/tmp/busted/node_modules/postcss/lib/container.js:306:20)
    at insertRules (/Users/nullstyle/src/tmp/busted/node_modules/postcss-import/index.js:217:17)
    at readImportedContent (/Users/nullstyle/src/tmp/busted/node_modules/postcss-import/index.js:185:3)
    at readAtImport (/Users/nullstyle/src/tmp/busted/node_modules/postcss-import/index.js:150:3)
    at transformAtImport (/Users/nullstyle/src/tmp/busted/node_modules/postcss-import/index.js:86:7)
    at Object.tryCatch [as try] (/Users/nullstyle/src/tmp/busted/node_modules/postcss-import/node_modules/postcss-message-helpers/index.js:53:12)
    at checkAtRule (/Users/nullstyle/src/tmp/busted/node_modules/postcss-import/index.js:85:16)
    at /Users/nullstyle/src/tmp/busted/node_modules/postcss/lib/container.js:218:22

Enhancement: Removing unused @chaset at-rulers and possible encoding convertions

Never used @charset at-rules myself and not really understand why somebody may want to make css files with different @charset values (importing css from external libraries perhaps?), but specificaition allows it.

Good idea will probably to do the following: If any of imported files have @charset, then convert file to UTF-8 from this charset and remove @charset at-rule.

But it is not really a urgent feature, it can be done sometimes later.

Throw an error when import statement have have braces

@import 'src/css/_foo'

:root {
  --color: #a12;
}

Omiting the ; make the root node to be part of the import statement in the AST.
@ai doesn't think of a simpler way to handle that in postcss itself because the parser is very flexible (which is a good thing).
So we might here throw an error or a message via postcss message api.

Add option to run a processor on imported AST

Convenient to run a linter on the fly. No extra processing.
Ideas:

  • change onImport option to pass all files + latest filename/ast
  • add an afterParse (or onParse) option that take filename + ast

Bug with Hash URL

Should ignore hash url.

@import url("#");

If the processed file with hash url we get an error:

/Users/blond/projects/postcss-import/node_modules/postcss-message-helpers/index.js:79
    throw err
          ^
Error: <css input>:15:1: Failed to find '#' from /Users/blond/projects/postcss-import
    in [ 
        /Users/blond/projects/postcss-import/test/fixtures/imports
    ]
    at <css input>:15:1
    at resolveFilename (/Users/blond/projects/postcss-import/index.js:326:11)
    at readAtImport (/Users/blond/projects/postcss-import/index.js:149:26)
    at transformAtImport (/Users/blond/projects/postcss-import/index.js:87:7)
    at Object.tryCatch [as try] (/Users/blond/projects/postcss-import/node_modules/postcss-message-helpers/index.js:53:12)
    at /Users/blond/projects/postcss-import/index.js:86:16
    at Array.forEach (native)
    at parseStyles (/Users/blond/projects/postcss-import/index.js:85:11)
    at /Users/blond/projects/postcss-import/index.js:67:5
    at PostCSS.process (/Users/blond/projects/postcss-import/node_modules/postcss/lib/postcss.js:79:28)
    at compareFixtures (/Users/blond/projects/postcss-import/test/index.js:22:6)

Joint plugin development

Hi!

I'm also trying to write import plugin and like to discuss if we can do it together and if yes how to do better do it.

The version that I'm writing right now will have following differences:

  1. It rebases relative assets from imported css files to new root (it's important if imported file was in a different directory).
  2. It works around the situation when one of the imports in files can't be expanded (see example below).

Import example.

This way all files will be imported:

@import "local1.css";
@import "http://cdn.google.com/external.css";
@import "local2.css";

This way import will be ignored by browser because @import can only be in the beginning of the file or after @charset of other @import ( see http://www.w3.org/TR/CSS2/syndata.html#at-rules ):

.local1 { color: red; }
@import "http://cdn.google.com/external.css";
.local2 { color: blue; }

I already wrote couple of helper plugins and libs that I'm planing to use with it:

How do you think, can we join out projects or is it better leave them separated?

Failed to find <file> from <path>

This error occurs multiple times, and I don't understand real issue here.

First, your README example doesn't work. If I use from option, I get:

TypeError: Property '0' of object [object Object],function AtImport(options) {
  // blah blah blah
} is not a function

If I don't use the from option, I get the Failed to find <file> from <path> error.

If I use the path option, it used to work with 3.2.0 version, but no longer work with 4.0.0. Still the Failed to find <file> from <path> error.

Any thought ?

Failing case with autoprefixer!

I am working off this cssnext version https://github.com/littlebits/cssnext/tree/feature/add-postcss-url which is bleeding edge.

I am trying to use it in my project and am noticing some strange behaviour that I'm pretty sure represents a breaking deviation from before. Namely the package normalize.css (yes, .css is literally in the package name) is causing all sorts of trouble for cssnext. I assume its due to postcss-import though honestly I just don't know yet.

Here is a screenshot of the error in my project dep (I've opened an editor into my littlebits-ui dep:

screen shot 2015-01-27 at 8 08 18 pm

When I uncomment that line, everything works but when it is active then cssnext fails with almost no help:

ERROR in ./~/css-loader!./~/cssnext-loader!./lib/index.css
TypeError: Cannot call method 'indexOf' of undefined

Other @imports work just fine. For instance if I move up one dependency closer to my project there is this index.css file with:

/*@import 'suitcss-base';*/
@import 'suitcss-components-button';
@import 'suitcss-utils-text';

As you can see I can import other suitcss packages just fine.

@necolas @MoOx Let me know any ideas you have about this.

@sokra How can I get a more useful error message from the build, even a stack trace please!

Plugin options are no longer passed in

Ever since 5bbe120 was merged in, I'm seeing that the plugin options no longer get passed in.

I'm using cssnext and I dove into cssnext/node_modules/postcss-import/index.js and added the following to the top of the AtImport function block to see what was happening:

function AtImport(options) {
  console.log("options:", options)
  process.exit()

And I get the following in my shell:

options: undefined

If, however, I pull index.js from the previous commit, c900ccc, I get the following:

options: { path: 'src/app/styles/blocks',
  plugins:
   [ { [Function: creator] postcss: [Object] },
     { [Function]
       postcssPlugin: 'postcss-bem-linter',
       postcssVersion: '4.1.11' } ] }

It must have something to do with replacing this:

/**
 * Expose the plugin.
 */
module.exports = AtImport

with this:

module.exports = postcss.plugin(
  "postcss-import",
  AtImport
)

But I'm not sure how that broke things.

Postcss-import combined with react hotloader

Hey there.

Has anyone gotten auto-reload (ReactHotloader) working using on imported css files using the postcss-import plugin? The problem I'm having is that any changes made in css files that get imported by a main css file do not to directly show up on screen.

I'd like to figure out whether this is an issue caused by my own setup, the import-plugin, ReactHotLoader, and whether there is a good solution for this.

I've created an example case in the following repo: https://github.com/0nn0/hotloader-postcss-imports/

You can produce the problem using the following steps.

  1. Check out Branch postcss-import-plugin
  2. Run npm install
  3. Run npm run start
  4. Open http://localhost:3000/
  5. Change background-color in styles.css (change will be directly visible)
  6. Change background-color in component.css (change will NOT be visible until you restart the app)

If I do not use the postcss-import plugin, then none of the postcss-plugins set in the webpack config will be applied on any of the to be imported css files, in this case components.css.

Any help would be much appreciated.

Relative imports don't work if no from option given

Let's assume the following project structure:

  • ./gulpfile.js
  • ./css/main.css
  • ./css/lists.css

main.css contains the following line: @import "lists.css";

This currently doesn't work without passing { path: ['css'] } to postcss-import. This is probably related to #7, but I feel like relative imports should just work despite of what postcss-import does after it decided that it's not a relative import (e.g., look for node_modules/lists.css/ or something like that).

Processing imported files

This is probably a misunderstanding on my part of how this works, but im having a few issues, where the modifications made by postcss to my files stop working once I put that code into an import file.

For example, im using postcss-map to create maps, and have this on my main css file:

header{
    background: map(colors, header, bg);
}

However once I pull that code into a partial file than I later import it stops working, and the text is outputted without any modification, meaning it won't replace that map call by the corresponding value.

My gulp file looks like this:


var gulp         = require('gulp');
var plumber      = require('gulp-plumber');
var browserSync  = require('browser-sync');
var postcss      = require('gulp-postcss');
var nestedcss    = require('postcss-nested');
var simplevars   = require('postcss-simple-vars');
var map          = require('postcss-map');
var atImport     = require('postcss-import');
var autoprefixer = require('autoprefixer');
var sourcemaps   = require('gulp-sourcemaps');
var config       = require('../config').markup;


var opts = {
    basePath: 'src/settings/',
    maps: [ 'colors.yml', 'typography.yml' ]
};

gulp.task('css', function () {
    var processors = [
        autoprefixer({browsers: ['last 1 version', 'ie 10']}),
        map(opts),
        nestedcss,
        simplevars,
        atImport
    ];
    return gulp.src('./src/css/main.css')
        .pipe( plumber() )
        .pipe( sourcemaps.init() )
        .pipe( postcss(processors) )
        .pipe( sourcemaps.write('.') )
        .pipe( gulp.dest('build/') )
        .pipe( browserSync.stream({match: "**/*.css"}) );
});

Any tips?

TypeError when using @import for local and remote stylesheets

If I have one or more @import pointing to an external URL (e.g. @import url("//hello.myfonts.net/count/");) and nothing else, postcss-import doesn't inline them. ๐Ÿ‘

However, if the stylesheet also has an @import pointing to a local stylesheet for inlining, I get the following:

/Projects/postcss-import-test/node_modules/postcss/lib/node.js:284
                if (p != root && p.parent && p.parent == root) {
                                  ^
TypeError: Cannot read property 'parent' of undefined
    at /Projects/postcss-import-test/node_modules/postcss/lib/node.js:284:35
    at /Projects/postcss-import-test/node_modules/postcss/lib/container.js:116:26
    at Root.each (/Projects/postcss-import-test/node_modules/postcss/lib/container.js:94:22)
    at Root.eachInside (/Projects/postcss-import-test/node_modules/postcss/lib/container.js:115:21)
    at Declaration.style (/Projects/postcss-import-test/node_modules/postcss/lib/node.js:282:18)
    at Declaration.style (/Projects/postcss-import-test/node_modules/postcss/lib/node.js:362:35)
    at Declaration.stringify (/Projects/postcss-import-test/node_modules/postcss/lib/declaration.js:19:27)
    at Rule.stringifyContent (/Projects/postcss-import-test/node_modules/postcss/lib/container.js:34:27)
    at Rule.stringifyBlock (/Projects/postcss-import-test/node_modules/postcss/lib/container.js:49:18)
    at Rule.stringify (/Projects/postcss-import-test/node_modules/postcss/lib/rule.js:23:14)

Also, if the stylesheet to be inlined only contains an empty declaration block (e.g. p {}), I don't get the error but do see:

@import url("http://hello.myfonts.net/count/");

undefinedp{}

Looks like something is creeping in with parsing, prepending that undefined, but haven't been able to get further than that.

Noticed this when bumping a project from [email protected] and [email protected] to [email protected] and [email protected]. Works as expected (ie. remote stylesheet @import ignored, local inlined) with the older versions.

Test case at this gist.

Support comma separated filenames for import

Using Sass it's possible to import using comma separated files, e.g:

@import
  'module1.pcss',
  'module2.pcss';

This would be great to have available from within this plugin as it tidies up your main stylesheet file.

Container#eachAtRule is deprecated. Node#before is deprecated.

I use postcss-import with postcss-cli as this:

postcss -u postcss-import ./index.css > test/bundle.css

My index.css:

@import 'other.css';

My other.css:

a {}

In terminal I get:

> postcss -u postcss-import ./index.css > test/bundle.css

Container#eachAtRule is deprecated. Use Container#walkAtRules instead.
Node#before is deprecated. Use Node#raws.before
[TypeError: Cannot read property 'before' of undefined]
...

Versions:

$ npm list postcss
[email protected] c:\path\to\xxx
โ”œโ”€โ”ฌ [email protected]
โ”‚ โ””โ”€โ”€ [email protected]
โ””โ”€โ”ฌ [email protected]
  โ””โ”€โ”€ [email protected]

Not sure whether it is postcss-cli or postcss-import issue.

Module build failed: TypeError: Cannot read property 'before' of undefined

I'm using postcss in a Webpack project using the postcss-loader. I'm looking to store my global vars in a single index.css file and pull that in where needed. As soon as I add the postcss-import plugin and an import statement I get the following error:

ERROR in ./~/css-loader?modules&localIdentName=[name]--[local]_[hash:base64:5]!./~/postcss-loader!./src/js/website.com/components/Button/Button.css
Module build failed: TypeError: Cannot read property 'before' of undefined
    at Stringifier.raw (/Users/username/Sites/website/node_modules/postcss-loader/node_modules/postcss/lib/stringifier.js:121:30)
    at Stringifier.body (/Users/username/Sites/website/node_modules/postcss-loader/node_modules/postcss/lib/stringifier.js:93:31)
    at Stringifier.root (/Users/username/Sites/website/node_modules/postcss-loader/node_modules/postcss/lib/stringifier.js:37:14)
    at Stringifier.stringify (/Users/username/Sites/website/node_modules/postcss-loader/node_modules/postcss/lib/stringifier.js:33:24)
    at _default.stringify (/Users/username/Sites/website/node_modules/postcss-loader/node_modules/postcss/lib/stringify.js:14:9)
    at _default.generateString (/Users/username/Sites/website/node_modules/postcss-loader/node_modules/postcss/lib/map-generator.js:231:14)
    at _default.generateMap (/Users/username/Sites/website/node_modules/postcss-loader/node_modules/postcss/lib/map-generator.js:189:14)
    at _default.generate (/Users/username/Sites/website/node_modules/postcss-loader/node_modules/postcss/lib/map-generator.js:271:25)
    at LazyResult.stringify (/Users/username/Sites/website/node_modules/postcss-loader/node_modules/postcss/lib/lazy-result.js:221:24)
    at /Users/username/Sites/website/node_modules/postcss-loader/node_modules/postcss/lib/lazy-result.js:158:27
    at lib$es6$promise$$internal$$tryCatch (/Users/username/Sites/website/node_modules/autoprefixer-core/node_modules/postcss/node_modules/es6-promise/dist/es6-promise.js:331:16)
    at lib$es6$promise$$internal$$invokeCallback (/Users/username/Sites/website/node_modules/autoprefixer-core/node_modules/postcss/node_modules/es6-promise/dist/es6-promise.js:343:17)
    at /Users/username/Sites/website/node_modules/autoprefixer-core/node_modules/postcss/node_modules/es6-promise/dist/es6-promise.js:891:13
    at Object.lib$es6$promise$asap$$flush [as _onImmediate] (/Users/username/Sites/website/node_modules/autoprefixer-core/node_modules/postcss/node_modules/es6-promise/dist/es6-promise.js:125:9)
    at processImmediate [as _immediateCallback] (timers.js:345:15)
 @ ./src/js/website.com/components/Button/Button.css 4:14-198

This is my loader:

{
    test: /\.(css)$/,
    loader: 'style-loader!css-loader?modules&localIdentName=[name]--[local]_[hash:base64:5]!postcss-loader'
}

โ€ฆ and the postcss config:

postcss: function () {
    return [
        require('postcss-import'),
        require('postcss-custom-properties'),
        require('postcss-mixins')
    ];
}

Any ideas?

@import not working on local and npm modules simultaneously

Hi!

I've been using rework and rework-npm like so:

@import "icon";

icon is a local package in this dir, structured as such:

app/styles/icon

package.json
index.css
lib/icon.css

package.json looks like this:

{
  "name": "icon",
  "description": "Symbols  that represent things",
  "version": "0.1.0",
  "style": "index.css",
  "main": "index.css",
  "files": [
    "index.css"
  ]
}

and my styles task looks like this:

    .pipe(postcss([
      inline({
        path: ['app/styles/']
      }),

but I'm getting this error:

[11:51:12] { errno: 28,
  code: 'EISDIR',
  syscall: 'read',
  name: 'Error',
  message: 'EISDIR, illegal operation on a directory',
  stack: 'Error: EISDIR, illegal operation on a directory\n    at Object.fs.readSync (fs.js:476:19)\n    at Object.fs.readFileSync (fs.js:310:28)\n    at readFile (/Users/vince/Projects/leveleleven/scorecard/client/node_modules/postcss-import/index.js:271:23)\n    at insertAtImportContent (/Users/vince/Projects/leveleleven/scorecard/client/node_modules/postcss-import/index.js:156:21)\n    at readAtImport (/Users/vince/Projects/leveleleven/scorecard/client/node_modules/postcss-import/index.js:133:3)\n    at checkAtRule (/Users/vince/Projects/leveleleven/scorecard/client/node_modules/postcss-import/index.js:66:5)\n    at /Users/vince/Projects/leveleleven/scorecard/client/node_modules/postcss/lib/container.js:233:26\n    at /Users/vince/Projects/leveleleven/scorecard/client/node_modules/postcss/lib/container.js:157:24\n    at Root._classProps.each.value (/Users/vince/Projects/leveleleven/scorecard/client/node_modules/postcss/lib/container.js:131:20)\n    at Root._classProps.eachInside.value (/Users/vince/Projects/leveleleven/scorecard/client/node_modules/postcss/lib/container.js:156:21)',
  showStack: false,
  showProperties: true,
  plugin: 'gulp-postcss' }
[

normal npm modules are working correctly. Any idea if I'm doing something wrong here?

Add glob.

What about adding feature like glob @import "css/**/*.css", @import "css/dir/*.css"?

Refactor (explode) index.js

This file is becoming huge. All functions accept too many parameters, it's going to be a pain to maintain if we don't do something :)

postcss-npm

There is nice idea of rework-npm module. I think we need same. Also some Rework users will think about move to PostCSS if we made it.

Should we integrate it to postcss-import or we can use @import support from postcss-import in some postcss-npm? Or postcss-npm should some kind of source of postcss-import?

5.0.2 introduces a bug

I don't really know the problem, but let's take 2 files:

/*file 1*/
@import 'file2.css';
.file1 {}
/*file 2*/
.file2--1 {}
.file2--2 {}

And add a console.log(styles.nodes[1].parent) on line index.js:67.

When using [email protected], you get 3 nodes in parent, while with [email protected], you only get 2 nodes, only those from file2.css. I checked your modifications, but my brain doesn't find where the problem is.

And this breaks some tests when using postcss-import with other modules.

Processing silently aborts on missing import

When importing a file that doesn't exist, postcss processing seems to abort suddenly (i'm using gulp-postcss; I get Starting 'build:postcss' but never a Finished, and my dest files aren't created).

It seems like it should either:

  • Continue processing and leave @import rule untouched
  • Continue processing and remove @import rule
  • Fail w/ an error

Browser jspm/SystemJS support

I want to use postcss-import with plugin-postcss(jspm/SystemJS plugin). But since postcss-import uses fs and resolve packages/calls it isn't compatible when trying to run it client side in the browser.

I am not sure on the best way to solve this other than using fetch and inlining when the promise resolves.


Related: I opened geelen/plugin-postcss#4 which will add the proper processing from option for nice path resolves.

Add support for bower packages

It would be great if postcss-import natively supported import of bower packages the same way it supports npm modules.

For example, it seems more logic to me to have normalize.css installed through Bower than through npm.

Thanks!

Glob fails with livereload

I'd like to preface this by saying I'm having a hard time isolating this bug.

I have an ember-cli app using Postcss with a number of plugins. The import plugin works fine for finding node modules, like normalize.css, and relative files (ie. "components/header"). However, when I enable globbing in the options object and try a number of syntaxes:

@import "components/*
@import "components/**/*
@import "components/*.css
@import "components/**/*.css

It works fine on first load, but upon saving a file and having livereload kick off a new build of the application the globbed components aren't included in the build, so in a way it fails silently. I initially thought it had to do with my settings or config, but then it shouldn't even work for the first load.

I was hoping to get some help in isolating this behaviour because I think this type of setup is likely fairly common.

Optimization by file content must skip "proxy" files

I've a main css file where I do:

@import "module-a";
@import "module-b";

Both modules have an index.css with @import "./src/styles/index.css";

If I compile, it only imports the first module, not the second. For instance, if I switch from a to b like that:

@import "module-b";
@import "module-a";

module-b will be imported but not module-a.

To fix it, I have to do that:

@import "module-a/src/styles/index.css";
@import "module-b/src/styles/index.css";

I'm inspecting this bug but if you have already an idea why, I'll be glad to hear.

import file with variables

I have question about using the postcss-import plugin with combination with simple vars plugin.

I have a set of files which I want to import to a main file. Here's an example structure.

  • main.css
    • variables.css
    • fileone.css
    • filetwo.css
// variables.css
$blue: #056ef0;
$foo: #ff00ff;
// fileone.css
address {
    color: $foo;
}
//filetwo.css
p {
    color: $blue;
}

I was expecting the output to parse the variables in fileone.css and filetwo.css and generate the end file like:

address {
    color: #ff00ff;
}
p {
    color: #056ef0;
}

but what i get in the end is:

address {
    color: $foo;
}
p {
    color: $blue;
}

So my variables are being ignore. My gulpfile looks like this:

var postcss = require('gulp-postcss'),
    gulp = require('gulp'),
    autoprefixer = require('autoprefixer-core'),
    mqpacker = require('css-mqpacker'),
    csswring = require('csswring'),
    atImport = require('postcss-import'),
    mixins = require('postcss-mixins'),
    vars = require('postcss-simple-vars'),
    nested = require('postcss-nested');

gulp.task('css', function () {
    var processors = [
        mixins,
        vars,
        nested,
        atImport,
        autoprefixer({browsers: ['last 4 version']}),
        mqpacker,
        // csswring
    ];
    return gulp.src('./assets/src/*.css')
        .pipe(postcss(processors))
        .pipe(gulp.dest('./assets/dest'));
});

gulp.task('default', [
    'css'
]);

Can anyone point me to the right direction as to how to get my variables to be picked up and parsed by the import plugin? Any examples would be appreciated.

osX asks for sudo to install

whenever I try to install through npm I get this error while all other postcss plugins does not asks for sudo

error: EACCES, mkdir '/Users/francis.thibault/.npm/glob/5.0.14'
npm ERR! at Error (native)
npm ERR! { [Error: EACCES, mkdir '/Users/francis.thibault/.npm/glob/5.0.14']...

expose @import list

for cssnext/cssnext-loader

as import uses its own filesystem, webpack needs to get a dependency map to watch the right files for the development mode

it then would be great to get a dependency map from this plugin

Use PostCSS 5.0

Seems like postcss.parse broke a AST in PostCSS 5.0 (because your plugin depends on PostCSS 4.x and uses 4.x parser, which generates 4.x nodes).

Can you update PostCSS in dependencies?

/cc @MoOx

Can we add the option to import underscored file names like Sass

In Sass you can import files with underscores without adding underscores in the code- When the file name is actually _my-file.scss :

@import "my-file.scss"
// or 
@import "my-file"

Unless I'm missing something it would be handy to add this. Having loads of underscores in the names makes it ugly to read and its also useful to have a prefix that's ignored so we can exclude the files from watch tasks etc

Thanks you

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.