Skip to content

Commit

Permalink
feat(errors): validate preset when filename is absent
Browse files Browse the repository at this point in the history
Closes #10154
  • Loading branch information
JLHwung committed Jul 9, 2019
1 parent 25f040c commit 0a5d100
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 4 deletions.
23 changes: 19 additions & 4 deletions packages/babel-core/src/config/full.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,17 +278,32 @@ const instantiatePlugin = makeWeakCache(
},
);

const validatePreset = (
preset: PresetInstance,
context: ConfigContext,
descriptor: UnloadedDescriptor,
): void => {
if (!context.filename) {
const { options } = preset;
if (options.test || options.include || options.exclude) {
throw new Error(
`Preset ${descriptor.name ||
""} requires filename, but it was not passed.`.replace(/\s{2}/, " "),
);
}
}
};

/**
* Generate a config object that will act as the root of a new nested config.
*/
const loadPresetDescriptor = (
descriptor: UnloadedDescriptor,
context: ConfigContext,
): ConfigChain | null => {
return buildPresetChain(
instantiatePreset(loadDescriptor(descriptor, context)),
context,
);
const preset = instantiatePreset(loadDescriptor(descriptor, context));
validatePreset(preset, context, descriptor);
return buildPresetChain(preset, context);
};

const instantiatePreset = makeWeakCache(
Expand Down
14 changes: 14 additions & 0 deletions packages/babel-core/test/config-chain.js
Original file line number Diff line number Diff line change
Expand Up @@ -1049,5 +1049,19 @@ describe("buildConfigChain", function() {
loadOptions({ filename, cwd: path.dirname(filename) }),
).toThrow(/Error while parsing JSON - /);
});

it("should throw when `test` presents but `filename` is not passed", () => {
expect(() => loadOptions({ test: /\.ts$/, plugins: [] })).toThrow(
/Configuration contains string\/RegExp pattern/,
);
});

it("should throw when `preset` requires `filename` but it was not passed", () => {
expect(() => {
loadOptions({
presets: [require("./fixtures/config-loading/preset4")],
});
}).toThrow(/Preset requires filename/);
});
});
});
6 changes: 6 additions & 0 deletions packages/babel-core/test/fixtures/config-loading/preset4.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = function() {
return {
test: /\.ts$/,
plugins: []
}
};

0 comments on commit 0a5d100

Please sign in to comment.