[Solved] SyntaxError: Cannot use import statement outside a module

Solve the syntaxerror: cannot use import statement outside a module problem

Originally, I wanted to test blob and format in the node environment. After importing relevant JS files, an error cannot use import statement outside a module occurs. Here are the following references to solve the problem:

    1. use commonjs syntax to bypass import
let Blob = require('blob-polyfill/Blob');

It can solve the problem of failed file import at present, but it means that you can’t use import to import in the future. The fundamental problem has not been solved. Of course, this is not my style. Then go to consult the data. What the elder brother said is well summarized as follows:

The error is reported because the node environment does not support ES6 syntax. We can install Babel jest, @Babel/core, @Babel/preset env to solve the problem (these plug-ins can convert ES6 code into Es5 so that the node environment can be recognized. Here I choose @Babel/preset env for installation). After installation, create babel.config.js file in the root log of the project: see the name of this file, Babel is configured; (similar to webpack.Config.JS),

module.exports = {
    "presets": [
        ["@babel/preset-env",
            {
                "targets":
                    { "node": true }
            }
        ]
    ]
}

Generally speaking, package.json is not configured with type, and it is equipped with type: type: "module". The problem is solved here. Finally, I also remembered that when I first used sass, I had to configure it to compile sass into CSS and be recognized by the environment (Longyin).

Read More: