Skip to content

Commit 5817cb0

Browse files
authored
feat(transform): node require (#134)
* transform: support node require * node require test * replace endsWith with regex
1 parent 9f94359 commit 5817cb0

4 files changed

Lines changed: 44 additions & 4 deletions

File tree

test/fixtures/example.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
module.exports = '.foo { color: blue; }'

test/fixtures/import-source-js.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
const sf = require('sheetify')
2+
3+
sf('./example.js')

test/import.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,35 @@ test('npm import', function (t) {
3838
}
3939
})
4040

41+
t.test('should import js file', function (t) {
42+
t.plan(1)
43+
44+
const expected = require(path.join(__dirname, 'fixtures/example.js'))
45+
46+
const ws = concat(function (buf) {
47+
const res = String(buf).trim()
48+
t.equal(res, expected, 'package was imported')
49+
})
50+
51+
const bOpts = { browserField: false }
52+
const bpath = path.join(__dirname, 'fixtures/import-source-js.js')
53+
browserify(bpath, bOpts)
54+
.transform(sheetify)
55+
.transform(function (file) {
56+
return through(function (buf, enc, next) {
57+
const str = buf.toString('utf8')
58+
this.push(str.replace(/sheetify\/insert/, 'insert-css'))
59+
next()
60+
})
61+
})
62+
.plugin('css-extract', { out: outFn })
63+
.bundle()
64+
65+
function outFn () {
66+
return ws
67+
}
68+
})
69+
4170
t.test('should emit an error on broken import', function (t) {
4271
t.plan(1)
4372

transform.js

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,18 @@ function transform (filename, options) {
135135
// (obj, fn) -> null
136136
function iterate (val, done) {
137137
if (val.css) return handleCss(val)
138-
fs.readFile(val.filename, 'utf8', function (err, css) {
139-
if (err) return done(err)
140-
val.css = css
138+
139+
if (/\.js$/.test(val.filename)) {
140+
delete require.cache[require.resolve(val.filename)]
141+
val.css = require(val.filename)
141142
handleCss(val)
142-
})
143+
} else {
144+
fs.readFile(val.filename, 'utf8', function (err, css) {
145+
if (err) return done(err)
146+
val.css = css
147+
handleCss(val)
148+
})
149+
}
143150

144151
function handleCss (val) {
145152
sheetify(val.css, val.filename, val.opts, function (err, css, prefix) {

0 commit comments

Comments
 (0)