Skip to content

Commit

Permalink
Use browser-resolve to ignore fs inlining (#523)
Browse files Browse the repository at this point in the history
  • Loading branch information
fathyb authored and devongovett committed Jan 14, 2018
1 parent dd26db3 commit bd9fd9f
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/visitors/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@ module.exports = {
},

CallExpression(path, asset) {
if (referencesImport(path, 'fs', 'readFileSync')) {
// See https://github.com/defunctzombie/node-browser-resolve#skip
let ignore =
asset.package &&
asset.package.browser &&
asset.package.browser.fs === false;

if (!ignore && referencesImport(path, 'fs', 'readFileSync')) {
let vars = {
__dirname: Path.dirname(asset.name),
__filename: asset.basename
Expand Down
20 changes: 19 additions & 1 deletion test/fs.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const assert = require('assert');
const {bundle, run} = require('./utils');
const {bundle, run, assertBundleTree} = require('./utils');

describe('fs', function() {
it('should inline a file as a string', async function() {
Expand Down Expand Up @@ -52,4 +52,22 @@ describe('fs', function() {
let output = run(b);
assert.equal(output, 'hello');
});

it('should not evaluate fs calls when package.browser.fs is false', async function() {
let b = await bundle(
__dirname + '/integration/resolve-entries/ignore-fs.js'
);

assertBundleTree(b, {
name: 'ignore-fs.js',
// empty.js is generated by require('fs'), it gets mocked with an empty module
assets: ['empty.js', 'ignore-fs.js', 'index.js'],
childBundles: []
});

let output = run(b);

assert.equal(typeof output.test, 'function');
assert.equal(output.test(), 'test-pkg-ignore-fs-ok');
});
});
5 changes: 5 additions & 0 deletions test/integration/resolve-entries/ignore-fs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import file from './pkg-ignore-fs'

export function test() {
return file()
}
9 changes: 9 additions & 0 deletions test/integration/resolve-entries/pkg-ignore-fs/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default () => {
try {
// We expect browser-resolve to replace fs with an empty module, so readFileSync will be undefined
return require('fs').readFileSync(__dirname + '/package.json')
}
catch(_) {
return 'test-pkg-ignore-fs-ok'
}
}
7 changes: 7 additions & 0 deletions test/integration/resolve-entries/pkg-ignore-fs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "pkg-ignore-fs",
"main": "index.js",
"browser": {
"fs": false
}
}

0 comments on commit bd9fd9f

Please sign in to comment.