The error message “Cannot use import statement outside a module” happens when the import keyword is located in an improperly configured JavaScript or TypeScript module.
In a JavaScript server-side runtime environment, this blunder usually results from importing syntax for modules written in ECMAScript (ES) when Node.js is expecting the required keyword used by the CommonJS module system.
TypeScript supports other module formats, but coding errors that complicate the ES and CommonJS approaches to importing modules also result in this error.
Read Also: How to make the first letter of a string uppercase in JavaScript
On the browser side, the error generally occurs when you don’t utilize a bundler for your JavaScript code files.
This article examines these three error sources and describes a solution for each environment.
How To Resolve the Error in Server-Side JavaScript
This section explains how to crack the error in server-side JavaScript environments.
Background
Node.js utilizes the CommonJS system’s required keyword by default. Thus, you’ll receive the familiar error unless you configure Node.js to support ES module syntax. Also, Node.js requires the .mjs extension to identify and work with ES modules.
Solution
Alternatively to utilizing .mjs, you can make older versions of Node.js consistent with the current ES module by utilizing bundlers or running Node.js with the –experimental-modules flag. Otherwise, you could set the kind field in the package.json file to module as follows:
Read Also: JavaScript: Double Not Operator?
{
"name": "test-package",
"version": "1.0.0",
"type": "module",
"main": "app.js",
"dependencies": { }
}
(Notice: You should contain the type property in the package.json file in all packages. This practice makes it more manageable to identify the module system in use and provide consistency among your libraries.)
Another method to avoid the error is to ensure that the import and export syntaxes are right and load properly. It’s essential to always use relative file paths, and file extensions for exports, named exports, and avoid default exports.
Here’s an example:
//module import
import { sampleFunction } from './sampleModule.js';
// function export
export function sampleFunction() {
// code goes here
}
Finally, you should confirm the compatibility of all third-party libraries with ES modules. For these details, refer to the library documentation for the package.json file. Alternatively, operate a bundler to transpile the code so a JavaScript environment can understand it.
Read Also: How do I use JavaScript to modify the URL without reloading the page?
How To Resolve the Error in TypeScript Environments
This section explains how to solve the error message in TypeScript environments.
Background
With modules, you can organize, reuse, and share code among numerous files in a project. ES supports external modules for sharing code among different files using the import and export keywords.
This error usually happens in TypeScript environments when operating the ES module syntax without configuring TypeScript to operate it. Since TypeScript is a superset of JavaScript, it defaults to using CommonJS syntax for imports, which uses demand instead of import. In this case, the import statement generates the error. Nevertheless, precisely configuring TypeScript is required for it to support ES modules.
You might also experience this error if you use the wrong file extension. For example, when using TypeScript in a Node.js environment with ES module syntax, the module you like to import must have the .mjs file extension instead of the regular .js.
Another typical source of the error is the improper configuration of the module field in your tsconfig.json or package.json files when operating bundlers like Webpack. However, you can use bundlers for ES modules in TypeScript by setting the module and mark fields in the tsconfig.json file to ECMAScript. Then, Webpack will comprehend the target environment and use the correct file extensions when transpiling the code.
Solution
To load ES modules utilizing a module loader like RequireJS or a bundler like Webpack, make the following additions to the tsconfig.json file:
{
"compilerOptions": {
"module": "es20215",
"target": "es20215",
"sourceMap": true
}
}
In the compiler options portion of the code above, the module and target fields are set to operate an es20215 module. With these expansions, you can utilize the import and export statements in a TypeScript environment without generating the error.
As TypeScript employs CommonJS by default, failing to modify the tsconfig.json file accordingly will result in the error message.
Fortunately, once you’ve placed the module and target fields to use an ECMAScript module, you can utilize the export statement to export a function or variable from a module and the import statement to load another module into the existing one’s scope. This procedure occurs in the code below:
// sum.ts
export function sum(a: number, b: number, c: number): number {
return a + b + c;
}
// main.ts
import { sum } from './sum';
console.log(add(4, 4, 9));
If you’re utilizing an older version of Node.js, you can enable ES module support by running your code with the –experimental-modules flag. It would help if you also used a bundler like Browserify, Webpack, or Rollup to bundle all the ES code and output it to a single file. Confirm that it’s in a version that browsers and old Node.js versions can comprehend and set up a Webpack.config.js file in the root of your project that defines the module type.
Here’s an instance extracted from the Webpack documentation:
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
extensions: ['.ts', '.js', '.mjs']
},
module: {
rules: [
{
test: /.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
experiments: {
outputModule: true
}
};
The assembled code is output to a bundle.js file in the dist directory of the project’s root directory.
You can also utilize polyfills like es-module-shims to target older browsers that don’t support ES modules’ import and export reports.
Read Also: javascript a tag – “Thinking in AngularJS” if I have a jQuery background?
How To Resolve the Error in Browser-Side JavaScript
This section guides you on how to crack the error in browser-side JavaScript environments.
Background
Most modern browsers, including Chrome, Edge, Firefox, and Safari, support ES modules, so you won’t be required to use browser polyfills, bundlers, or transpilers.
You also don’t require them if you use the React or Vue JavaScript-based frontend libraries because they support the ES imports and exports fields by default. However, elder browsers don’t support ES syntax, so they need these tools for cross-platform compatibility.
The most general reason for the error in an older browser is when a page’s HTML files do not include the type=”module” attribute. In this scenario, the error happens because JavaScript running on the web doesn’t include default support for ES module syntax. For JavaScript code sent across the wire, you might experience a cross-origin resource-sharing error when attempting to load an ES module from a distinct domain.
Solution
To control the module error in an older browser, provide that you’re using the correct script tag attribute — type=”module” — in the root HTML file. Alternatively, you can utilize Webpack to transpile the code so that older browsers can comprehend it.
To use the type=”module” attribute, contain the following line in your root HTML file:
<script type="module" src="app.js"></script>
It’s equally essential to ensure the import file paths are correct and that you’re using the correct import syntax.
Additionally, you can visit sites like Can I Use to ensure browser compatibility for ES modules.
Finally, since using the .js file extension is standard practice, you can set the type attribute in the module’s HTML file script tag as a workaround. Setting this attribute to module conveys the browser to disregard the .js extension and treat the file as a module.
Recap
The “Cannot use import statement outside a module” error may appear for different reasons, depending on whether you’re in a browser-side or server-side JavaScript environment. Wrong syntax, improper configurations, and unsupported file extensions remain a few of the most typical sources of this error.
While most modern browsers support ES modules, you must confirm that older browsers are compatible. Bundlers like Webpack let you to compile all source code with their dependences to a single output that older browsers can comprehend.
Leave a Reply