Type module js ошибка

package.json

{
  ...
  "type": "module",
  "dependencies": {
    "vue": "^3.2.36"
  }
}

index.html

<!DOCTYPE html>
<html lang="ru">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <script src="main.js"></script>
  </body>
</html>

main.js
import Vue from 'vue'

Ошибка

Uncaught SyntaxError: Cannot use import statement outside a module (at main.js:1:1)


  • Вопрос задан

  • 324 просмотра

Самый простой вариант:

index.html

...
<script src="main.js" type="module"></script>
...

main.js

import 'node_modules/vue/dist/vue.global.js';
...

Пригласить эксперта

не хватает type=»module» у тега script, если вы сборщики не используете

Чтобы все заработало, нужно не только дописать type=module тегу script, но и запустить локальный сервер. Используйте икстеншин live server (или что-то подобное) вашего редактора кода, чтобы все заработало


  • Показать ещё
    Загружается…

21 сент. 2023, в 20:54

10000 руб./за проект

21 сент. 2023, в 20:40

20000 руб./за проект

21 сент. 2023, в 20:29

2000 руб./за проект

Минуточку внимания

If you are having trouble with the error: To load an ES module, set “type” – “module” in JavaScript, let’s follow this article. I will give you some solutions to fix it. Let’s go into detail now.

The error happens when you try using ES6 syntax like import-export without setting in file ‘package.json’. So you get a conflict.

Example of error:

const sum = (str) => {
  console.log(str);
};
import logText from "./logText";
logText("Hello");
Error: (node:17308) Warning: To load an ES module, set "type": "module" in the package.json or
use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
D:\Workspace\CTV WORK\javascript\index.js:1
import logText from "./logText";
^^^^^^
 
SyntaxError: Cannot use import statement outside a module
	at ...

How to fix this error?

Solution: Setting ‘package.json.’

You will have to initiate the project if you want to use nodejs or ES6 modules syntax.

Step 1: Initiate project

You can init your project by this command:

npm init

Result:

{
  "name": "javascript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Step 2: Set ‘type’

You will have to set the ‘type’ property in the ‘package.json’ file to load ES modules.

Example:

{
  "name": "javascript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
 
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC" 
}

And your code will run.

Now you can import functions, variables, etc., from another file.

Example:

import logText from "./dialog.js";
dialog.logText("Hello"); 
 
const logText= (str) => {
  console.log(str);
};

function response(){
    console.log("Hi")
}

export default logText

Output:

Hello

You can also import more than one, like the code below.

Example:

const logText= (str) => {
  console.log(str);
};

function response(){
    console.log("Hi")
}

export {logText,response}
import * as dialog from "./dialog.js";
dialog.logText("Hello");
dialog.response();

Here I import logText and response function separately. Then I use the ‘*’ symbol to import all functions that I export to the dialog.js file. You can also export separate like this:

import {logText,response} from "./dialog.js";
dialog.logText("Hello");
dialog.response();

Output:

Hello
Hi

Summary

In this tutorial, I showed and explained how to fix the error: To load an ES module, set “type” – “module” in JavaScript. You should set ‘type’ property in package.json to ‘module.’

Maybe you are interested:

  • TypeError (intermediate value)(…) is not a function in JS
  • TypeError: indexOf is not a function in JavaScript
  • Identifier has already been declared Error in JavaScript
  • document.getElementsByClass is not a Function in JavaScript

Brent Johnson

Hello, guys! I hope that my knowledge in HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, Python, MySQL, and npm computer languages may be of use to you. I’m Brent Johnson, a software developer.


Name of the university: HOU
Major: IT
Programming Languages: HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, PyThon, MySQL, npm

Table of Contents

Hide

  1. What is SyntaxError: cannot use import statement outside a module?
  2. How to fix SyntaxError: cannot use import statement outside a module?
    1. Solution 1 – Add “type”: “module” to package.json 
    2. Solution 2 – Add type=”module” attribute to the script tag
    3. Solution 3 – Use import and require to load the modules
  3. Configuration Issue in ORM’s
  4. 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 a package.json file, initialize it by using the npm 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.

0. The short answer

You need to install and run a local web server. — For a suggestion on how,
read on.

1. The basics

I tried a simple HTML file – index.html – as follows:

<!-- index.html - minimal HTML to keep it simple -->
<html>
<head>
  <meta charset="UTF-8">
  <link rel="shortcut icon" href="#">
</head>
<body>
  <h1>Hello world!</h1>
  <p>Experimenting with JavaScript modules.</p>
  <script type="module" src="js/functions.js"></script>
</body>
</html>

In the subfolder js I put the JavaScript file functions.js:

// js/functions.js
alert('Hello');

When double-clicking index.html, my default web browser – Firefox 89.0
(64-bit) – shows the following, after pressing F12.
Notice how the JavaScript code is not running:

JavaScript not working in browser.

The error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/stackexchange/reproduce/jsModule/moduleNW/basics/js/functions.js. (Reason: CORS request not http).

A cheating «solution» is to (temporarily) remove type="module" from the HTML
code.
The alert then displays without errors.

But I want to run the JavaScript code as a module, so I put back
type="module" in the HTML.

2. Install and run a local web server

To run it as a module, it needs to run on a web server.
Thus, if you want to run the code on your own computer, you will need to
(install and) start a local web server.
One currently popular alternative is live-server.
Here is what worked for me.

  • Open a terminal. (On Windows: cmd.exe.)
  • Type npm and hit Enter to see if Node.js is installed.
  • If you get command not found, download at https://nodejs.org/en/download/
    and install. 1
    (On Ubuntu, you can try sudo apt install -y nodejs.)
  • Install live-server: npm install live-server -g.
  • Change directory to where your page lives: cd <path-to-index.html>.
  • Start the server: live-server .
    (Should open localhost:8080 in your default browser and show the alert.
    See below.)

JavaScript running locally on live-server.

Note 1.
I am on Windows 10, but the above instructions should work fine on Linux and
macOS too.
Note 2.
Here I used Firefox 89.0, but I have tried Google Chrome 91.0 as well.
The only notable difference is the CORS error message, which in Chrome reads:
Access to script at 'file:///C:/stackexchange/reproduce/jsModule/basics/js/functions.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

3. Exporting and importing

Next I create a new folder demo2 containing the following demo2.html:

<!-- demo2.html - even shorter HTML for simplicity -->
<body>
  <h1>Hello world!</h1>
  <p>Javascript modules.</p>
  <script type="module" src="js/main.js"></script>
</body>

I also create the following three JavaScript files in the subfolder js:

// js/module1.js
export function hi () { console.log('Hi from module 1.'); }

and

// js/module2.js
export function howdy () { console.log('Howdy from module 2!'); }

and

// js/main.js
import { hi } from './module1.js';
import { howdy } from './module2.js';
hi();
howdy();

Now I run live-server from the terminal in the folder where demo2.html
resides.
This time I start by typing
live-server --port=1234 --entry-file=demo2.html
and hitting Enter. Screenshot:

JavaScript running when called from several sub-modules.

References:

  • Installing Node.js live-server
  • The live-server docs
  • Live-server can’t find the file specified
  • Export and Import

1 On Windows 10, I once needed to
repair the installation.

Cannot use import statement outside a module [React TypeScript Error Solved]

When building a web application, you may encounter the SyntaxError: Cannot use import statement outside a module error.

This error might be raised when using either JavaScript or TypeScript in the back-end. So you could be working on the client side with React, Vue, and so on, and still run into this error.

You can also encounter this error when working with JavaScript on the client side.

In this article, you’ll learn how to fix the SyntaxError: Cannot use import statement outside a module error when using TypeScript or JavaScript with Node.

You’ll also learn how to fix the error when working with JavaScript on the client side.

How to Fix the TypeScript SyntaxError: Cannot use import statement outside a module Error

In this section, we’ll work with a basic Node server using Express.

Note that if you’re using the latest version of TypeScript for your Node app, the tsconfig.json file has default rules that prevent the SyntaxError: Cannot use import statement outside a module error from being raised.

So you’re most likely not going to encounter the SyntaxError: Cannot use import statement outside a module error if you:

  • Install the latest version of TypeScript, and are using the default tsconfig.json file that is generated when you run tsc init with the latest version.
  • Setup TypeScript correctly for Node and install the necessary packages.

But let’s assume you’re not using the latest tsconfig.json file configurations.

Here’s an Express server that listens on port 3000 and logs «Hello World!» to the console:

import express from "express"

const app = express()

app.listen("3000", (): void => {
    console.log("Hello World!")
    // SyntaxError: Cannot use import statement outside a module
})

The code above looks as though it should run perfectly but the SyntaxError: Cannot use import statement outside a module is raised.

This is happening because we used the import keyword to import a module: import express from "express".

To fix this, head over to the tsconfig.json file and scroll to the modules section.

You should see a particular rule like this under the modules section:

/* Modules */
"module": "esnext" 

To fix the problem, change the value «esnext» to «commonjs».

That is:

/* Modules */
"module": "commonjs"

How to Fix the JavaScript SyntaxError: Cannot use import statement outside a module Error

Fixing the SyntaxError: Cannot use import statement outside a module error when using vanilla JS is a bit different from TypeScript.

Here’s our server:

import express from "express";

const app = express();

app.listen(3000, () => {
    console.log("Hello World!");
    // SyntaxError: Cannot use import statement outside a module
});

We’re getting the SyntaxError: Cannot use import statement outside a module error for the same reason — we used the import keyword to import a module.

To fix this, go to the package.json file and add "type": "module",. That is:

{
  "name": "js",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}

Now you can use the import keyword without getting an error.

To fix this error when working with JavaScript on the client side (without any frameworks), simply add the attribute type="module" to the script tag of the file you want to import as a module. That is:

<script type="module" src="./add.js"></script>

Summary

In this article, we talked about the SyntaxError: Cannot use import statement outside a module error in TypeScript and JavaScript.

This error mainly occurs when you use the import keyword to import a module in Node.js. Or when you omit the type="module" attribute in a script tag.

We saw code examples that raised the error and how to fix them when working with TypeScript and JavaScript.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Type mismatch vba excel ошибка массив
  • Type mismatch vba excel ошибка runtime 13
  • Type mismatch in expression access ошибка
  • Txd workshop ошибка list index out of bounds
  • Ts vms ошибка подключения что делать