I am getting this error SyntaxError: Cannot use import statement outside a module
when trying to import from another javascript file. This is the first time I’m trying something like this. The main file is main.js
and the module file is mod.js
.
main.js:
import * as myModule from "mod";
myModule.func();
mod.js:
export function func(){
console.log("Hello World");
}
How can I fix this? Thanks
asked Jun 20, 2020 at 16:56
3
In order to use the import syntax (ESModules), you need to add the following to your package.json at the top level:
{
// ...
"type": "module",
}
If you are using a version of Node earlier than 13, you additionally need to use the --experimental-modules
flag when you run the program:
node --experimental-modules program.js
answered Jun 20, 2020 at 17:02
Achraf GhellachAchraf Ghellach
1,4861 gold badge8 silver badges6 bronze badges
6
Use commonjs syntax instead of es module syntax:
module.exports.func = function (){
console.log("Hello World");
}
and
const myMod = require("./mod")
myMod.func()
Otherwise, if you want to use es modules you have to do as the answer by Achraf Ghellach suggests
answered Jun 20, 2020 at 17:07
gautam1168gautam1168
5715 silver badges15 bronze badges
4
I recently encountered this problem. This solution is similar to the top rated answer but with some ways I found worked for me.
In the same directory as your modules create a package.json file and add "type":"module"
. Then use import {func} from "./myscript.js";
. The import style works when run using node.
answered Jun 10, 2021 at 9:17
In addition to the answers above, note by default(if the «type» is omitted) the «type» is «commonjs». So, you have explicitly specify the type when it’s «module». You cannot use an import statement outside a module.
answered Apr 19, 2021 at 21:35
LekiaLekia
951 silver badge12 bronze badges
If you are in the browser (instead of a Node environment), make sure you specify the type="module"
attribute in your script
tag. If you want to use Babel, then it must be type="text/babel" data-plugins="transform-es2015-modules-umd" data-type="module"
.
answered Apr 7, 2022 at 21:56
SimoneSimone
1,1891 gold badge15 silver badges27 bronze badges
For browser(front end):
add type = «module» inside your script tag i.e
<script src="main.js" type="module"></script>
For nodejs:
add "type": "module"
, in your package.json file
answered May 16, 2022 at 4:18
kob003kob003
1,7082 gold badges10 silver badges17 bronze badges
I had this issue trying to run mocha tests with typescript. This isn’t directly related to the answer but may help some.
This article is quite interesting. He’s using a trick involving cross-env
, that allows him to run tests as commonjs module type. That worked for me.
// package.json
{
...
"scripts": {
"test": "cross-env TS_NODE_COMPILER_OPTIONS='{ "module": "commonjs" }' mocha -r ts-node/register -r src/**/*.spec.ts"
}
}
answered Feb 10, 2022 at 14:50
johnnyBoyjohnnyBoy
1153 silver badges12 bronze badges
0
I got the same issue but in another module (python-shell).
I replaced the code as follows:
import {PythonShell} from 'python-shell'; (original code)
let {PythonShell} = require('python-shell')
That solved the issue.
answered Apr 8, 2022 at 21:12
SnowcatSnowcat
4507 silver badges15 bronze badges
I’m trying to use classes in pure JavaScript, so I’m facing the error «Uncaught SyntaxError: Cannot use import statement outside a module» and can’t solve it.
File1.js — Main file
import example from "./file2";
var test = new example();
File2.js — Class file
export default class example {
constructor() {
console.log("hello world");
}
}
asked Oct 12, 2019 at 19:53
2
Add files with type="module"
:
<script src="file1.js" type="module" ></script>
KyleMit♦
36.9k64 gold badges451 silver badges647 bronze badges
answered Oct 12, 2019 at 19:56
marzelinmarzelin
10.4k2 gold badges30 silver badges49 bronze badges
5
A little late, but for newcomers to this quandary, you can convert both files to a module js .mjs
. From there you can do what you were trying:
File1.mjs — Main file
import example from "./file2.mjs";
File2.mjs — Class file
export default class example {
constructor() {
console.log("hello world");
}
}
answered Jan 27, 2022 at 16:37
Mister PeaMister Pea
941 silver badge4 bronze badges
Table of Contents
Hide
- What is SyntaxError: cannot use import statement outside a module?
- How to fix SyntaxError: cannot use import statement outside a module?
- Solution 1 – Add “type”: “module” to package.json
- Solution 2 – Add type=”module” attribute to the script tag
- Solution 3 – Use import and require to load the modules
- Configuration Issue in ORM’s
- Conclusion
The Uncaught SyntaxError: cannot use import statement outside a module mainly occurs when developers use the import statement on the CommonJS instead of require statement.
What is SyntaxError: cannot use import statement outside a module?
There are several reasons behind this error. First, let us look at each scenario and solution with examples.
- If you are using an older Node version < 13
- If you are using a browser or interface that doesn’t support ES6
- If you have missed the type=”module” while loading the script tag
- If you missed out on the “type”: “module” inside the package.json while working on Node projects
Many interfaces till now do not understand ES6 Javascript features. Hence we need to compile ES6 to ES5 whenever we need to use that in the project.
The other possible reason is that you are using the file that is written in the ES6 module directly inside your code. It means you are loading the src file/directory instead of referring to the dist directory, which leads to a SyntaxError.
Usually, we use a bundled or dist file that is compiled to ES5/Javascript file and then import the modules in our code.
How to fix SyntaxError: cannot use import statement outside a module?
There are 3 ways to solve this error. Let us take a look at each of these solutions.
Solution 1 – Add “type”: “module” to package.json
If you are working on Node.js or react applications and using import statements instead of require
to load the modules, then ensure your package.json
has a property "type": "module"
as shown below.
Adding “type”: “module” to package.json will tell Node you are using ES6 modules(es modules), which should get solve the error.
If you would like to use the ES6 module imports in Node.js, set the type
property to the module
in the package.json
file.
{
// ...
"type": "module",
// ...
}
If you are using TypeScript, we need to edit the tsconfig.json file and change the module property to “commonjs
“, as shown below.
ts.config file
Change the ts.config
file as shown below to resolve the Uncaught SyntaxError: cannot use import statement outside a module error.
"target": "esnext",
"module": "esnext",
to
"target": "esnext",
"module": "commonjs",
If this error mainly occurs in the TypeScript project, ensure that you are using a ts-node to transpile into Javascript before running the .ts file. Node.js can throw an error if you directly run the typescript file without transpiling.
Note: If your project does not have apackage.json
file, initialize it by using thenpm init -y
command in the root directory of your project.
Solution 2 – Add type=”module” attribute to the script tag
Another reason we get this error is if we are loading the script from the src directory instead of the built file inside the dist directory.
It can happen if the src file is written in ES6 and not compiled into an ES5 (standard js file). The dist files usually will have the bundled and compiled files, and hence it is recommended to use the dist folder instead of src.
We can solve this error by adding a simple attribute type="module"
to the script, as shown below.
<script type="module" src="some_script.js"></script>
Solution 3 – Use import and require to load the modules
In some cases, we may have to use both import and require statements to load the module properly.
For Example –
import { parse } from 'node-html-parser';
parse = require('node-html-parser');
Note: When using modules, if you get ReferenceError: require is not defined
, you’ll need to use the import
syntax instead of require
.
Configuration Issue in ORM’s
Another possible issue is when you are using ORM’s such as typeORM and the configuration you have set the entities to refer to the source folder instead of the dist folder.
The src folder would be of TypeScript file and referring the entities to .ts files will lead to cannot use import statement outside a module error.
Change the ormconfig.js to refer to dist files instead of src files as shown below.
"entities": [
"src/db/entity/**/*.ts", // Pay attention to "src" and "ts" (this is wrong)
],
to
"entities": [
"dist/db/entity/**/*.js", // Pay attention to "dist" and "js" (this is the correct way)
],
Conclusion
The Uncaught SyntaxError: cannot use import statement outside a module occurs if you have forgotten to add type="module"
attribute while loading the script or if you are loading the src files instead of bundled files from the dist folder.
We can resolve the issue by setting the “type”: “module” inside the package.json while working on Node projects. If we are loading the Javascript file then we need to add the attribute type="module"
to the script tag.
Related Tags
- import,
- require,
- SyntaxError
Sign Up for Our Newsletters
Get notified on the latest articles
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
Ошибка “SyntaxError: Cannot use import statement outside a module” возникает, когда интерпретатор JavaScript встречает оператор import
вне модуля.
В JavaScript модуль – это код, выполняемый в своей собственной области видимости, отдельной от глобальной области видимости. Операторы импорта могут использоваться только внутри модуля, но не в глобальной области видимости.
Эта ошибка может возникнуть в любой среде JavaScript, в том числе и в Node.js. Однако более вероятно ее появление в средах, которые не поддерживают использование операторов импорта в глобальной области видимости, например, в старых JavaScript-движках или браузерах.
Содержание
- Исправление для HTML
- Исправление для Node.js
- Исправление для TypeScript
Исправление для HTML
Чтобы устранить проблему для HTML-скриптов, необходимо установить атрибут type
элемента <script>
, чтобы указать тип скрипта, включенного в элемент.
Если атрибут type
имеет значение “module”, браузер будет знать, что сценарий является модулем JavaScript, и будет выполнять его как таковой.
Это позволит вам использовать операторы импорта внутри сценария.
Вот пример:
<!-- when loading raw JS -->
<script type="module"></script>
<!-- when loading external files -->
<script type="module" src="assets/script.js"></script>
В качестве альтернативы вы можете использовать такой инструмент, как Babel, для транспонирования вашего кода, который преобразует утверждения импорта в более старый синтаксис, который можно использовать в глобальной области видимости. Затем вы можете включить транспонированный код в свой HTML-документ.
Исправление для Node.js
Чтобы использовать импорт модулей ES6 в Node.js, вы можете установить поле type
в файле package.json вашего проекта, чтобы указать, что ваш проект использует модули ES6.
Вот пример:
{
"name": "my-project",
"type": "module",
...
}
После добавления поля type в файл package.json вы можете использовать оператор import
в JavaScript-файлах вашего проекта без необходимости использования специальных флагов.
import myModule from './my-module';
// keep in mind that for local files, you have to append the .js extension to the module, like so:
import myModule from './my-module.js';
// if not you'll get the error: "[ERR_MODULE_NOT_FOUND]: Cannot find module".
Этот подход имеет несколько преимуществ. Во-первых, он не требует использования специальных флагов при запуске интерпретатора Node.js, что делает его более удобным. Во-вторых, он позволяет другим инструментам, таким как бандлеры и линтеры, распознать, что в вашем проекте используются модули ES6, что упрощает использование этих инструментов в вашем проекте.
Исправление для TypeScript
Чтобы использовать систему модулей CommonJS в проекте TypeScript, вам нужно включить опции компилятора allowSyntheticDefaultImports и esModuleInterop в конфиге TypeScript.
Эти опции позволяют TypeScript рассматривать импортируемые значения так, как будто они имеют экспорт по умолчанию, даже если они его не имеют, и использовать синтаксис импорта с модулями CommonJS.
tsconfig.json:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
...
}
}
Эти параметры поддерживаются только в TypeScript 3.8 и более поздних версиях.
Другая возможность заключается в том, что вы пытаетесь запустить свои файлы TypeScript с помощью команды node, а не с помощью такого инструмента, как ts-node, для транспонирования и запуска.
В этом случае вы можете использовать ts-node для транспонирования и запуска ваших файлов, чтобы исправить ошибку.
Если у вас появились вопросы про то, как устранить ошибку “SyntaxError: Cannot use import statement outside a module”, мы будем рады ответить вам в комментариях ниже.
Are you getting the SyntaxError Cannot use import statement outside a module in JavaScript? In this article, I will discuss how to resolve this error in JavaScript.
You can receive this error for various reasons in JavaScript, it can be the Node.js or NPM that may cause the error. Or it may be the ECMAScript 6 that is not getting supported by the browser you are using.
You use the below methods discussed to get this error fixed that you are getting while you are trying to import a library in JavaScript.
Method 1: Using Module in Package.JSON file
The first method that you can use the get rid of this error is using the "type":"module"
code in your package.json file present inside your project folder.
Filename: package.json
{
//----
"type": "module",
//---
//---
}
As you can see in the above code, I have used the import syntax function instead of require
method that can usually cause the SyntaxError. Hence to remove this syntax error you need to import[1] the module in the package JSON.
Also, make sure that you do not run TypeScripts scripts present in your project independently as those scripts can also cause this error or you can go into an infinite loop instead.
Method 2: Adding Module to Script Tag
If you are still getting the error then you may try adding the type as a module in the script tag as well. Sometimes adding a module to a package JSON file may not work and it may work if you add it to an individual script tag that is throwing an error for you.
<script type="module" src="../src/main.js"></script>
Since type module specifies to JavaScript that you can import the module you want to use for this script tag and hence removes the chances of getting StandardError.
Method 3: Using Require Instead of Import
You can use the require
method of JavaScript if none of the above methods are working for you. But you need to add it differently as mentioned below in the example code snippet.
//Suppose you want to import fetch from 'getFetch'
fetch = require('getFetch')
Note: Here inside the bracket after require you need to enter your library name and before equals what you want to import from that library.
Using the above code, I was able to fix my error for SyntaxError for importing the module. This usually works for Node.
Method 4: Enable EMCAScript 6 in NodeJs
Another method that can help you fix this SyntaxError is enabling the ECMAScript 6 in your project if it is already not enabled. To enable you to need to follow the below steps.
//Open the Terminal and Type and Press Enter
npm install --save esm
or
node -r esm server.js
Why SyntaxError: Cannot use import statement outside a module Occurs?
Numerous interfaces continue to be incompatible with the ES6 JavaScript syntax and functionality. As a result, if ES6 is used in a file or project, it must be built to ES5 first.
The SyntaxError: Cannot use import statement outside of a module error could occur if you attempt to execute the file independently. You have not yet installed and configured an ES6 compiler such as Babel, or the file path in your runscript is incorrect/is not the compiled file.
If you wish to proceed without using a compiler, the optimal way is to use ES5 syntax, which in this example would be var ms = require(./ms.js);. This can be updated later as necessary, or better yet, configure your compiler and ensure that your file/project is compiled prior to running. Additionally, ensure that your run script is running the compiled file, which is typically named dist, build, or whatever you named it and that the path to the compiled file in your runscript is correct.
Wrap Up
I hope you were able to fix the SyntaxError using the methods listed above. As to resolve this error I have listed around four methods that you can use to resolve this issue.
If you are still not able to resolve this issue then please let me know in the comment section. Also, let me know if you know a better method to resolve these issues other than the one discussed above I will be happy to add it here.
If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.
Further Read:
- How To Remove A Specific item From An Array
- Best Udemy JavaScript Course 2021
#typescript #ts-node #es6-modules
Вопрос:
У меня есть script.ts
досье:
import path from 'path'
Если я побегу ts-node script.ts
, это сработает нормально.
Теперь я перемещаю файл в ./node-modules/.bin/script.ts
. Если я запущу ts-node ./node-modules/.bin/scripts.ts
, это не сработает:
(node:38262) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
xxx/node_modules/.bin/script.ts:1
import path from 'path'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at main (/xxx/.nvm/versions/node/v12.22.1/lib/node_modules/ts-node/src/bin.ts:198:14)
at Object.<anonymous> (/xxx/.nvm/versions/node/v12.22.1/lib/node_modules/ts-node/src/bin.ts:288:3)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
Я попытался вставить type: module
свой package.json
файл «это не работает», и я не могу использовать расширение .mjs
, так как это файл машинописного текста.
Как я могу сделать так, чтобы скрипт машинописи node_modules
работал так же, как и снаружи node_modules
??
Мой tsconfig.json
:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"lib": ["es2017"],
"moduleResolution": "node",
"outDir": "dist",
"types": ["node"],
"sourceMap": true
},
"include": ["src/**/*", "./node_modules/bin/script.ts"]
}
Комментарии:
1. Я попытался запустить ваш скрипт в папке верхнего уровня различных моих проектов (фактически унаследовав tsconfig.json от каждого). Я обнаружил, что в моих проектах nextjs и react, где модуль был «esnext», я столкнулся с той же ошибкой, о которой вы сообщили. В моих бэкенд-проектах, где модуль был «commonjs», у меня не было проблем. Поэтому я думаю, что это связано с тем, как ваша среда ожидает, что модули будут составлены в разных местах.
2. Разве не более общепринято, чтобы все в node_modules было перенесено на javascript, а не на машинописный текст? Я бы ожидал, что что-то, отображающееся в виде ячейки в node_modules, попадет туда через скрипт сборки npm, чтобы превратить typescript в нужный модуль javascript. Возможно, в поведении, которое вы видите, заложено сильное предположение об этом.
3. Нет, это сценарий машинописи, он не создан, потому что он импортирует другие файлы машинописи. Он находится в node_modules для совместного использования в нескольких проектах. Я просто хочу, чтобы он вел себя так, как если бы он был на высшем уровне. Я отредактирую свой ответ, чтобы поместить свой
tsconfig
4. Вы можете создавать сценарии машинописи, которые импортируют другие файлы машинописи. Это довольно фундаментальный аспект машинописи. Возможно, вы имеете в виду, что он не может быть построен, потому что вы хотите иметь возможность динамически редактировать файлы машинописи, которые он импортирует, не выполняя каждый раз этап сборки? Понимание некоторых ваших мотивов для того, чтобы не создавать модуль, но все же помещать его в node_modules, помогло бы респондентам.
5. Нет, это сценарий машинописи, а не сценарий js, я не могу его создать, он динамически импортирует локальные файлы машинописи из источников верхнего уровня, и я хочу легко обновить его
node_modules
. Я просто хочу отправить этот сценарий в другое хранилище и использоватьts-node
, но, по-видимомуts-node
, не могу запускать сценарии изnode_modules
. Кроме того, сценарий уже написан, я не собираюсь его рефакторинговать.
Answer by Florence Hendrix
I have a component that has props that are components.,
Is it a reasonable assumption that the best singers perform the lead roles?
,
Using two different maps on one atlas page
PropertyCardNew example:
```jsx
import FavoriteBorder from '@material-ui/icons/FavoriteBorder'
import Favorite from '@material-ui/icons/Favorite'
;<PropertyCardNew
images={
[
{
url: 'https://www.commerciallistings.cbre.co.uk//resources/fileassets/GB-Plus-480572/09e35192/11%20Strand%201_Photo_1_small.jpg',
alt: "An Image"
},
{
url: 'https://www.commerciallistings.cbre.co.uk//resources/fileassets/GB-Plus-480572/09e35192/11%20Strand%201_Photo_1_small.jpg',
alt: "An Image"
}
]
}
title="PricewaterhouseCoopers"
favIcon={{
icon: FavoriteBorder,
iconSelected: Favorite,
}}
subTitle="4th floor"
street="313 Stoughton Rd Edgerton, WI 53534-1132"
date="September"
desks="20+"
rent="$5600"
labels={{
date: 'date',
desks: 'desks',
rent: 'Monthly rent',
link: 'Details',
}}
link="https://commerciallistings.cbre.co.uk"
/>
```
Answer by Capri Rodgers
And Execute to create React App
npx create-react-app my-app
cd my-app
npm start
Answer by Rory Kemp
I’m trying to make an example of my component in the Markdown file (.md). The problem is when I try to import something inside this markdown file:,When I go to the component it says:
Error: import or require() statements can be added only by editing a Markdown example file: ../../utils/validation,Yes, me too. I have the error if I try to import any of the package.json dependencies except for react.
import { validateEmail } from '../../utils/validation';
initialState = {
value: 'asdas',
}
function updateValue(name, value) {
setState({ [name]: value });
}
<Input
placeholder="Name"
value={value}
type="text"
required={true}
name="value"
onChangeFunction={updateValue}
validations={[validateEmail]}
/>;
Answer by Tessa Townsend
In my case I’m using nextJs, and I solved my problem removing «next/babel» preset when I’m on Test enviroment (For any reason, using «next/babel», console shows the error: «SyntaxError: Cannot use import statement outside a module»):,/c/Users/newbe/play/edgauge/cvu-prototype-portal/node_modules/crossfilter2/src/index.js:1,What worked for me was changing the modules option of Babel’s ENV preset from false to auto.
module.exports = {
verbose: true,
preset: 'react-native-web'
}
Answer by Rafael Doyle
Use ref prop as a function and assign a reference to a local variable:,You should pass glob patterns, for example, use **/components/Button.js instead of components/Button.js.,Import these components in your examples:
ref
Answer by Westley Bryant
关于javascript — react-styleguidist-以Component作为 Prop 的示例-SyntaxError:无法在模块外部使用import语句,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/59776808/
,
javascript — 如何在 react-styleguidist 中添加具有依赖项的组件示例
,
原文
标签
javascript
reactjs
react-styleguidist
Component example:
```jsx
import FavoriteBorder from '@material-ui/icons/FavoriteBorder'
import Favorite from '@material-ui/icons/Favorite'
return (
<Component
favIcon={{
icon: FavoriteBorder,
iconSelected: Favorite,
}}
/>
)
```
SyntaxError: Cannot use import statement outside a module
事实证明;
是解决此问题的关键。
PropertyCard新示例:
```jsx
import FavoriteBorder from '@material-ui/icons/FavoriteBorder'
import Favorite from '@material-ui/icons/Favorite'
;<PropertyCardNew
images={
[
{
url: 'https://www.commerciallistings.cbre.co.uk//resources/fileassets/GB-Plus-480572/09e35192/11%20Strand%201_Photo_1_small.jpg',
alt: "An Image"
},
{
url: 'https://www.commerciallistings.cbre.co.uk//resources/fileassets/GB-Plus-480572/09e35192/11%20Strand%201_Photo_1_small.jpg',
alt: "An Image"
}
]
}
title="PricewaterhouseCoopers"
favIcon={{
icon: FavoriteBorder,
iconSelected: Favorite,
}}
subTitle="4th floor"
street="313 Stoughton Rd Edgerton, WI 53534-1132"
date="September"
desks="20+"
rent="$5600"
labels={{
date: 'date',
desks: 'desks',
rent: 'Monthly rent',
link: 'Details',
}}
link="https://commerciallistings.cbre.co.uk"
/>
```
Answer by Ryder Cole
SyntaxError: невозможно использовать оператор import вне функций модуля Firebase
,
Uncaught SyntaxError: невозможно использовать оператор import вне модуля
,
Javascript ошибка модуля SyntaxError: невозможно использовать инструкцию import вне модуля
У меня есть компонент, который имеет реквизит, который является компонентами.
Component example:
```jsx
import FavoriteBorder from '@material-ui/icons/FavoriteBorder'
import Favorite from '@material-ui/icons/Favorite'
return (
<Component
favIcon={{
icon: FavoriteBorder,
iconSelected: Favorite,
}}
/>
)
```
Ошибка
SyntaxError: Cannot use import statement outside a module
Answer by Evelynn Gray
This is a copy from https://github.com/facebook/jest/issues/6229 which is closed and not fixed still
Jest throws error «SyntaxError: Cannot use import statement outside a module» for libraries imported from node_modules.,??? Developer Ready: A comprehensive JavaScript testing solution. Works out of the box for most JavaScript projects.,I just changed the import into jest.mock and still get Promise error.
yarn add --dev jest
Answer by Emmaline Giles
More Details Refer