Describe the bug
When compiling in node (with next.js, for example) or running Jest test, Validator always throws the following error whenever anything is imported.
For example, I have a React component that imports blacklist from validator (this happens with any import though).
import blacklist from 'validator/es/lib/blacklist';
Works fine in development, but when I run jest locally, I get the following error:
{import assertString from './util/assertString';
^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1258:14)
at Object.<anonymous> (src/utils/src/string.js:1:1)
OR in the CI for next.js (a different project, but same issue
/home/circleci/repo/node_modules/validator/es/lib/isURL.js:1
import assertString from './util/assertString';
^^^^^^
SyntaxError: Cannot use import statement outside a module
Additional context
Validator.js version: 13.5.2
Node.js version: 10.13.0 and 12.18.4
OS platform: MacOS
Hi @sklawren, can you provide an example repo, please?
It's super easy to replicate. It's 100% reproducible with a brand new CRA project.
npx create-react-app validator-testnpm i -S validatorAdd a file called utils.js (or whatever):
import blacklist from 'validator/es/lib/blacklist';
export const sanitize = str => blacklist(str, 'a-z');
import {sanitize} from './utils';
import './App.css';
function App() {
const value = sanitize('a10c');
return (
<div className="App">
{value}
</div>
);
}
export default App;
npm start - Works fine. You should see '10' in the browser.npm test - Crashes. ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import assertString from './util/assertString';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import blacklist from 'validator/es/lib/blacklist';
| ^
2 |
3 | export const sanitize = str => blacklist(str, 'a-z');
4 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (src/string.js:1:1)
Try looking at facebook/create-react-app#9938 because this is a jest "problem" and not a validator.js one :)
I tried that and it didn't work. What did work was changing it to:
import blacklist from 'validator/lib/blacklist';
I guess this doesn't tree-shake, but it works.
@sklawren
i have the same issue described above, and I solved using jest.config options, transform, and transformIgnorePattern option.
if you don't use typescript, you can use babel-jest instead of ts-jest

Looks like the issue is related to jest and not validator . Thank you @P-iknow for providing the answer.
Most helpful comment
I tried that and it didn't work. What did work was changing it to:
I guess this doesn't tree-shake, but it works.