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)


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

    28 окт. 2022

  • 267 просмотров

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

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 (или что-то подобное) вашего редактора кода, чтобы все заработало


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

22 июн. 2023, в 09:14

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

22 июн. 2023, в 09:12

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

22 июн. 2023, в 09:08

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

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

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.

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:WorkspaceCTV WORKjavascriptindex.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.

Consider supporting my work if you though that was helpful

Introduction

When developing apps of scripts using Node JS you may encounter this error:

SyntaxError: Cannot use import statement outside a module

There are several ways to fix this, in this post we go over the various different ways there are to fix this error so you can chose the best one for your use case.

Why does this error occur?

Node is a great platform to develop your apps on, however, as any ecosystem is comes with some shortcomings. One such drawback to Javascript is that it has become a fragmented ecosystem.

Node JS was released in 2009, way before modern JavaScript became a thing. In fact, it’s Node JS (among others) that sparked the interest of thousands of developers to adopt it as their main development tool. Historically there has been a lack of standardisation for common programming concepts such as organising your code in modules, importing and exporting them across your code base.

One of the earlier projects that unified the way we import and export modules, packages or functions was CommonJS. Node adopted this convention from the beginning and it’s still the default convention for all Node versions.

Since Node version 13, however, Node.js has also broad support for a more modern API for managing modules, which es known as ES Modules.

Node JS still uses CommonJS as it’s default version of JavaScript, so when you get a SyntaxError: Cannot use import statement outside a module error, this is because you’re trying to write code using the ES Modules syntax (modern JavaScript) in a project that Node believes to be CommonJS.

While ES Modules give you access to a more modern and readable way of managing your imports using the import / export API instead of CommonJS’ require, you do need to tell Node.js you intend to use this API.

The fix for 99% of projects

Simply tell Node JS your project should use ES Modules instead of CommonJS. This can be done by adding 1 simple line of code to your package.json file:

{
  ...
  "type": "module",
  ...
}

By simply adding "type": "module" to your package.json file you’re telling Node to use ES Modules as the JS version for this project, and your issue should be resolved.

The fix for Browser based projects

If you’re developing a browser based app, you can also run into the same issue. The fix is equally simple there.

If you import a JS script similar to this, for example:

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

All you need to add is type="module" into the script tag like this:

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

The fix for Typescript projects

To fix the SyntaxError: Cannot use import statement outside a module error you need to change 2 files:

  • package.json
  • tsconfig.json

Add "type": "module" to your package.json just like the fix for any Node.js project

{
  ...
  "type": "module",
  ...
}

Make sure your tsconfig.json file has these 2 properties set to these values:

{
  ...
  "target": "esnext",
  "module": "commonjs",
  ...
}

  • Tx800fw epson ошибка принтера
  • Tx117 общая ошибка принтера
  • Tx pr50u10 ошибка 14
  • Twrp ошибка монтирования system
  • Twrp ошибка 255 при резервном копировании