Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use includes where appropriate #4412

Merged
merged 4 commits into from Feb 21, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 4 additions & 4 deletions cli/run/index.ts
Expand Up @@ -26,13 +26,13 @@ export default async function runRollup(command: Record<string, any>): Promise<v
}

if (inputSource && inputSource.length > 0) {
if (inputSource.some((input: string) => input.indexOf('=') !== -1)) {
if (inputSource.some((input: string) => input.includes('='))) {
command.input = {};
inputSource.forEach((input: string) => {
const equalsIndex = input.indexOf('=');
const value = input.substr(equalsIndex + 1);
let key = input.substr(0, equalsIndex);
if (!key) key = getAliasName(input);
const value = input.substring(equalsIndex + 1);
const key = input.substring(0, equalsIndex) || getAliasName(input);

command.input[key] = value;
});
} else {
Expand Down
2 changes: 1 addition & 1 deletion docs/05-plugin-development.md
Expand Up @@ -788,7 +788,7 @@ export default function addProxyPlugin() {
if (resolution && !resolution.external) {
// we pass on the entire resolution information
const moduleInfo = await this.load(resolution);
if (moduleInfo.code.indexOf('/* use proxy */') >= 0) {
if (moduleInfo.code.includes('/* use proxy */')) {
return `${resolution.id}?proxy`;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Chunk.ts
Expand Up @@ -605,7 +605,7 @@ export default class Chunk {
const source = module.render(renderOptions).trim();
renderedLength = source.length();
if (renderedLength) {
if (options.compact && source.lastLine().indexOf('//') !== -1) source.append('\n');
if (options.compact && source.lastLine().includes('//')) source.append('\n');
this.renderedModuleSources.set(module, source);
magicString.addSource(source);
this.usedModules.push(module);
Expand Down
2 changes: 1 addition & 1 deletion src/finalisers/iife.ts
Expand Up @@ -38,7 +38,7 @@ export default function iife(
}: NormalizedOutputOptions
): Bundle {
const { _, cnst, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
const isNamespaced = name && name.indexOf('.') !== -1;
const isNamespaced = name && name.includes('.');
const useVariableAssignment = !extend && !isNamespaced;

if (name && useVariableAssignment && !isLegal(name)) {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/getExportMode.ts
Expand Up @@ -33,7 +33,7 @@ export default function getExportMode(
}
exportMode = 'default';
} else {
if (format !== 'es' && format !== 'system' && exportKeys.indexOf('default') !== -1) {
if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
warn(errMixedExport(facadeModuleId, name));
}
exportMode = 'named';
Expand Down
4 changes: 2 additions & 2 deletions src/utils/options/mergeOptions.ts
Expand Up @@ -87,7 +87,7 @@ function getCommandOptions(rawCommandOptions: GenericConfigObject): CommandConfi
? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
const [id, variableName] = globalDefinition.split(':');
globals[id] = variableName;
if (external.indexOf(id) === -1) {
if (!external.includes(id)) {
external.push(id);
}
return globals;
Expand Down Expand Up @@ -156,7 +156,7 @@ const getExternal = (
const configExternal = config.external as ExternalOption | undefined;
return typeof configExternal === 'function'
? (source: string, importer: string | undefined, isResolved: boolean) =>
configExternal(source, importer, isResolved) || overrides.external.indexOf(source) !== -1
configExternal(source, importer, isResolved) || overrides.external.includes(source)
: ensureArray(configExternal).concat(overrides.external);
};

Expand Down
3 changes: 1 addition & 2 deletions src/utils/path.ts
Expand Up @@ -10,8 +10,7 @@ export function isRelative(path: string): boolean {
}

export function normalize(path: string): string {
if (path.indexOf('\\') == -1) return path;
return path.replace(/\\/g, '/');
return path.includes('\\') ? path.replace(/\\/g, '/') : path;
}

export { basename, dirname, extname, relative, resolve } from 'path';
2 changes: 1 addition & 1 deletion src/watch/watch.ts
Expand Up @@ -163,7 +163,7 @@ export class Task {
this.invalidated = true;
if (details.isTransformDependency) {
for (const module of this.cache.modules) {
if (module.transformDependencies.indexOf(id) === -1) continue;
if (!module.transformDependencies.includes(id)) continue;
// effective invalidation
module.originalCode = null as never;
}
Expand Down
2 changes: 1 addition & 1 deletion test/browser/index.js
Expand Up @@ -17,7 +17,7 @@ runTestSuiteWithSamples('browser', resolve(__dirname, 'samples'), (dir, config)
bundle = await rollup({
input: 'main',
onwarn: warning => {
if (!(config.expectedWarnings && config.expectedWarnings.indexOf(warning.code) >= 0)) {
if (!(config.expectedWarnings && config.expectedWarnings.includes(warning.code))) {
throw new Error(
`Unexpected warnings (${warning.code}): ${warning.message}\n` +
'If you expect warnings, list their codes in config.expectedWarnings'
Expand Down
17 changes: 8 additions & 9 deletions test/chunking-form/index.js
@@ -1,26 +1,25 @@
const path = require('path');
const rollup = require('../../dist/rollup');
const { basename, resolve } = require('path');
const { chdir } = require('process');
const { rollup } = require('../../dist/rollup');
const { runTestSuiteWithSamples, assertDirectoriesAreEqual } = require('../utils.js');

const FORMATS = ['es', 'cjs', 'amd', 'system'];

runTestSuiteWithSamples('chunking form', path.resolve(__dirname, 'samples'), (dir, config) => {
runTestSuiteWithSamples('chunking form', resolve(__dirname, 'samples'), (dir, config) => {
(config.skip ? describe.skip : config.solo ? describe.only : describe)(
path.basename(dir) + ': ' + config.description,
basename(dir) + ': ' + config.description,
() => {
let bundle;

for (const format of FORMATS) {
it('generates ' + format, async () => {
process.chdir(dir);
chdir(dir);
bundle =
bundle ||
(await rollup.rollup({
(await rollup({
input: [dir + '/main.js'],
onwarn: warning => {
if (
!(config.expectedWarnings && config.expectedWarnings.indexOf(warning.code) >= 0)
) {
if (!(config.expectedWarnings && config.expectedWarnings.includes(warning.code))) {
throw new Error(
`Unexpected warnings (${warning.code}): ${warning.message}\n` +
'If you expect warnings, list their codes in config.expectedWarnings'
Expand Down
2 changes: 1 addition & 1 deletion test/cli/samples/external-modules-auto-global/_config.js
Expand Up @@ -6,6 +6,6 @@ module.exports = {
'rollup main.js --format iife --globals mathematics:Math,promises:Promise --external promises',
execute: true,
stderr(stderr) {
assert.strictEqual(stderr.indexOf('(!)'), -1);
assert.ok(!stderr.includes('(!)'));
}
};
2 changes: 1 addition & 1 deletion test/cli/samples/external-modules/_config.js
Expand Up @@ -5,6 +5,6 @@ module.exports = {
command: 'rollup main.js --format cjs --external=path,util',
execute: true,
stderr(stderr) {
assert.strictEqual(stderr.indexOf('(!)'), -1);
assert.ok(!stderr.includes('(!)'));
}
};
14 changes: 6 additions & 8 deletions test/form/index.js
@@ -1,16 +1,16 @@
const assert = require('assert');
const { existsSync, readFileSync } = require('fs');
const path = require('path');
const rollup = require('../../dist/rollup');
const { basename, resolve } = require('path');
const { rollup } = require('../../dist/rollup');
const { normaliseOutput, runTestSuiteWithSamples } = require('../utils.js');

const FORMATS = ['amd', 'cjs', 'system', 'es', 'iife', 'umd'];

runTestSuiteWithSamples('form', path.resolve(__dirname, 'samples'), (dir, config) => {
runTestSuiteWithSamples('form', resolve(__dirname, 'samples'), (dir, config) => {
const isSingleFormatTest = existsSync(dir + '/_expected.js');
const itOrDescribe = isSingleFormatTest ? it : describe;
(config.skip ? itOrDescribe.skip : config.solo ? itOrDescribe.only : itOrDescribe)(
path.basename(dir) + ': ' + config.description,
basename(dir) + ': ' + config.description,
() => {
let bundle;
const runRollupTest = async (inputFile, bundleFile, defaultFormat) => {
Expand All @@ -20,12 +20,10 @@ runTestSuiteWithSamples('form', path.resolve(__dirname, 'samples'), (dir, config
process.chdir(dir);
bundle =
bundle ||
(await rollup.rollup({
(await rollup({
input: dir + '/main.js',
onwarn: warning => {
if (
!(config.expectedWarnings && config.expectedWarnings.indexOf(warning.code) >= 0)
) {
if (!(config.expectedWarnings && config.expectedWarnings.includes(warning.code))) {
warnings.push(warning);
}
},
Expand Down
Expand Up @@ -3,6 +3,6 @@ const assert = require('assert');
module.exports = {
description: 'should delete use asm from function body if it is not the first expression',
code(code) {
assert.equal(code.indexOf('use asm'), -1);
assert.ok(!code.includes('use asm'));
}
};
Expand Up @@ -3,8 +3,8 @@ const assert = require('assert');
module.exports = {
description: 'detect side effect in member expression assignment when not top level',
code(code) {
assert.equal(code.indexOf('function set(key, value) { foo[key] = value; }') >= 0, true, code);
assert.equal(code.indexOf('set("bar", 2);') >= 0, true, code);
assert.equal(code.indexOf('set("qux", 3);') >= 0, true, code);
assert.ok(code.includes('function set(key, value) { foo[key] = value; }'), code);
assert.ok(code.includes('set("bar", 2);'), code);
assert.ok(code.includes('set("qux", 3);'), code);
}
};
2 changes: 1 addition & 1 deletion test/function/samples/preload-cyclic-module/_config.js
Expand Up @@ -18,7 +18,7 @@ module.exports = {
const resolution = await this.resolve(source, importer, { skipSelf: true, ...options });
if (resolution && !resolution.external) {
const moduleInfo = await this.load(resolution);
if (moduleInfo.code.indexOf('/* use proxy */') >= 0) {
if (moduleInfo.code.includes('/* use proxy */')) {
return `${resolution.id}?proxy`;
}
}
Expand Down
@@ -1,18 +1,18 @@
const assert = require('assert');
const path = require('path');
const { join } = require('path');

module.exports = {
description: 'includes a relative external module only once (two external deps)',
options: {
external: [path.join(__dirname, './foo.js'), path.join(__dirname, './first/foo.js')]
external: [join(__dirname, './foo.js'), join(__dirname, './first/foo.js')]
},
context: {
require(required) {
assert(['./foo.js', './first/foo.js'].indexOf(required) !== -1, 'required wrong module');
assert.ok(['./foo.js', './first/foo.js'].includes(required), 'required wrong module');
return required === './foo.js' ? 'a' : 'b';
}
},
exports(exports) {
assert(exports === 'ab' || exports === 'ba', 'two different modules should be required');
assert.ok(exports === 'ab' || exports === 'ba', 'two different modules should be required');
}
};
4 changes: 2 additions & 2 deletions test/function/samples/transparent-dynamic-inlining/_config.js
Expand Up @@ -3,8 +3,8 @@ const assert = require('assert');
module.exports = {
description: 'Dynamic import inlining when resolution id is a module in the bundle',
code(code) {
assert.equal(code.indexOf('import('), -1);
assert.notEqual(code.indexOf('Promise.resolve('), -1);
assert.ok(!code.includes('import('));
assert.ok(code.includes('Promise.resolve('));
},
exports(exports) {
assert.deepEqual(exports, { y: 42 });
Expand Down
15 changes: 7 additions & 8 deletions test/misc/iife.js
@@ -1,5 +1,5 @@
const assert = require('assert');
const rollup = require('../../dist/rollup');
const { rollup } = require('../../dist/rollup');
const { loader } = require('../utils.js');
const { compareError } = require('../utils.js');

Expand All @@ -17,7 +17,7 @@ function runIifeTest(code, outputOptions) {
const bundleName = outputOptions.name.split('.')[0];
const globals = { external: 'external', __exports: {} };
runTestCode(
bundleName && bundleName.indexOf('@') === -1
bundleName && !bundleName.includes('@')
? `${code}if (typeof ${bundleName} !== 'undefined') __exports.${bundleName} = ${bundleName};`
: code,
globals
Expand All @@ -35,12 +35,11 @@ function getIifeExports(global, outputOptions) {
}

function getIifeCode(inputCode, outputOptions) {
return rollup
.rollup({
input: 'input',
external: ['external'],
plugins: [loader({ input: inputCode })]
})
return rollup({
input: 'input',
external: ['external'],
plugins: [loader({ input: inputCode })]
})
.then(bundle =>
bundle.generate({ format: 'iife', globals: { external: 'external' }, ...outputOptions })
)
Expand Down
6 changes: 3 additions & 3 deletions test/misc/umd.js
@@ -1,5 +1,5 @@
const assert = require('assert');
const rollup = require('../../dist/rollup');
const { rollup } = require('../../dist/rollup');
const { loader } = require('../utils.js');

function runTestCode(code, thisValue, globals) {
Expand Down Expand Up @@ -60,7 +60,7 @@ function runAmdTest(code, outputOptions) {
}
})
) || {};
return defineArgs[0].indexOf('exports') === -1 ? result : module.exports;
return defineArgs[0].includes('exports') ? module.exports : result;
}

function runIifeTestWithThis(code, outputOptions) {
Expand Down Expand Up @@ -119,7 +119,7 @@ function getIifeExports(global, outputOptions) {
}

async function getUmdCode(inputCode, outputOptions) {
const bundle = await rollup.rollup({
const bundle = await rollup({
input: 'input',
external: ['external'],
plugins: [loader({ input: inputCode })]
Expand Down
Expand Up @@ -3,6 +3,6 @@ const assert = require('assert');
module.exports = {
description: 'removes sourcemap comments',
async test(code) {
assert.strictEqual(code.indexOf('sourceMappingURL'), -1);
assert.ok(!code.includes('sourceMappingURL'));
}
};
Expand Up @@ -3,6 +3,6 @@ const assert = require('assert');
module.exports = {
description: 'removes existing inline sourcemaps',
async test(code) {
assert.strictEqual(code.indexOf('sourceMappingURL'), -1);
assert.ok(!code.includes('sourceMappingURL'));
}
};
2 changes: 1 addition & 1 deletion test/utils.js
Expand Up @@ -140,7 +140,7 @@ function runSamples(samplesDir, runTest, onTeardown) {

function runTestsInDir(dir, runTest) {
const fileNames = getFileNamesAndRemoveOutput(dir);
if (fileNames.indexOf('_config.js') >= 0) {
if (fileNames.includes('_config.js')) {
loadConfigAndRunTest(dir, runTest);
} else if (fileNames.length === 0) {
console.warn(`Removing empty test directory ${dir}`);
Expand Down