Skip to content

Commit

Permalink
Change resolve behavior (#249)
Browse files Browse the repository at this point in the history
Use default resolver when custom resolve does not return an
absolute path.
  • Loading branch information
RyanZim authored Nov 21, 2016
1 parent 3352a37 commit a15e402
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 7 deletions.
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,12 @@ files).
Type: `Function`
Default: `null`

You can overwrite the default path resolving way by setting this option.
This function gets `(id, basedir, importOptions)` arguments and returns full
path, array of paths or promise resolving paths.
You can use [resolve](https://github.com/substack/node-resolve) for that.
You can provide a custom path resolver with this option. This function gets
`(id, basedir, importOptions)` 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](https://github.com/substack/node-resolve) for this.

#### `load`

Expand Down
13 changes: 10 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,18 @@ function resolveImportId(
: options.root

return Promise.resolve(options.resolve(stmt.uri, base, options))
.then(function(resolved) {
if (!Array.isArray(resolved)) {
resolved = [ resolved ]
.then(function(paths) {
if (!Array.isArray(paths)) {
paths = [ paths ]
}

return Promise.all(paths.map(function(file) {
// Ensure that each path is absolute:
if (!path.isAbsolute(file)) return resolveId(file, base, options)
return file
}))
})
.then(function(resolved) {
// Add dependency messages:
resolved.forEach(function(file) {
result.messages.push({
Expand Down
22 changes: 22 additions & 0 deletions test/custom-resolve.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import test from "ava"
import compareFixtures from "./helpers/compare-fixtures"
import postcss from "postcss"
import atImport from ".."
import path from "path"

test.serial("should accept file", t => {
Expand Down Expand Up @@ -43,3 +45,23 @@ test.serial("should accept promised array of files", t => {
},
})
})

test(
"should apply default resolver when custom doesn't return an absolute path",
function(t) {
return postcss()
.use(atImport({
resolve: path => {
return path.replace("foo", "imports/bar")
},
load: p => {
t.is(p, path.resolve("fixtures/imports", "bar.css"))
return "/* comment */"
},
}))
.process(`@import "foo.css";`, { from: "fixtures/custom-resolve-file" })
.then(result => {
t.is(result.css, "/* comment */")
})
}
)

0 comments on commit a15e402

Please sign in to comment.