Browse Source

throw error on duplicated import

contingency-plan
Rich Harris 10 years ago
parent
commit
40bc464e9f
  1. 8
      src/Module.js
  2. 20
      src/utils/getLocation.js
  3. 2
      src/utils/replaceIdentifiers.js
  4. 5
      test/samples/duplicate-import-specifier-fails/_config.js
  5. 2
      test/samples/duplicate-import-specifier-fails/main.js

8
src/Module.js

@ -5,6 +5,7 @@ import MagicString from 'magic-string';
import analyse from './ast/analyse';
import { has } from './utils/object';
import { sequence } from './utils/promise';
import getLocation from './utils/getLocation';
const emptyArrayPromise = Promise.resolve([]);
@ -76,6 +77,13 @@ export default class Module {
const localName = specifier.local.name;
const name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
if ( has( this.imports, localName ) ) {
const err = new Error( `Duplicated import '${localName}'` );
err.file = this.path;
err.loc = getLocation( this.code.original, specifier.start );
throw err;
}
this.imports[ localName ] = {
source,
name,

20
src/utils/getLocation.js

@ -0,0 +1,20 @@
export default function getLocation ( source, charIndex ) {
const lines = source.split( '\n' );
const len = lines.length;
let lineStart = 0;
let i;
for ( i = 0; i < len; i += 1 ) {
const line = lines[i];
const lineEnd = lineStart + line.length + 1; // +1 for newline
if ( lineEnd > charIndex ) {
return { line: i + 1, column: charIndex - lineStart };
}
lineStart = lineEnd;
}
throw new Error( 'Could not determine location of character' );
}

2
src/utils/replaceIdentifiers.js

@ -53,4 +53,4 @@ export default function replaceIdentifiers ( statement, snippet, names ) {
}
}
});
}
}

5
test/samples/duplicate-import-specifier-fails/_config.js

@ -1,9 +1,12 @@
var path = require( 'path' );
var assert = require( 'assert' );
module.exports = {
description: 'disallows duplicate import specifiers',
error: function ( err ) {
assert.ok( false ); // TK - pick an error message
assert.equal( err.file, path.resolve( __dirname, 'main.js' ) );
assert.deepEqual( err.loc, { line: 1, column: 12 });
assert.ok( /Duplicated import/.test( err.message ) );
}
};

2
test/samples/duplicate-import-specifier-fails/main.js

@ -1,2 +1,2 @@
import { a, a } from './exporter';
import { a, a } from './foo';
assert.equal(a, 1);

Loading…
Cancel
Save