PorcupineTits
PorcupineTits

Reputation: 21

SyntaxError: import declarations may only appear at top level of a module. Using express, no webpack

I am trying to import a npm module in the front end script. It is saying modules must be on top level to import but it is at the top level from what I can tell. Maybe my web server is messing with my code. I am unsure.

The code is ugly right now because I am trying to get everything situated.

I have already tried

<script type='module' src='./js/scripts.js'></script>

scripts.js

import axios from 'axios';


function getQueryStringValue (key) {  
    return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));  
}  
const query = getQueryStringValue('code');

class chime {
    constructor(code) {
        this.code = code;
    };
    async logIn() {
        const response = await axios.post('url', {
            'client_id': '',
            'client_secret': '',
            'grant_type': '',
            'redirect_uri': 'https://localhost:3000',
            'code': this.code
        });

        console.log(response);
    }
    test() {
        console.log(this.code);
    }
}

if (query) {
    const client = new chime(query);

    client.logIn();

};
var express = require('express')
var fs = require('fs')
var https = require('https')
var app = express()
const path = require('path');

const publicPath = path.join(__dirname, '../public');
const port = 3000;

app.use(express.static(publicPath));



app.get('*', (req, res) => {
    res.sendFile(path.join(publicPath, '/index.html'));
});


https.createServer({
  key: fs.readFileSync(path.join(__dirname + '/ssl/server.key')),
  cert: fs.readFileSync(path.join(__dirname+ '/ssl/server.cert'))
}, app)
    .listen(3000, function () {
    console.log('Example app listening on port 3000! Go to https://localhost:3000/')
    });

I am wanting to be able to import npm modules.

Upvotes: 2

Views: 23535

Answers (3)

zhiqiang shu
zhiqiang shu

Reputation: 19

Spent 2 hours and finally find a solution, the first thing you need to do is

npm i parcel-bundler -D

then package.json add the following two-line of codes

"scripts": {
"dev": "parcel index.html",
"build": "parcel build index.html"
}

finally

npm run dev. 

and if you still have trouble, please open this link it just saves me so many hours.

Upvotes: 0

Lagu Longa
Lagu Longa

Reputation: 211

A quick and dirty way is to use the cdn:

 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

put it in your html file above your JavaScript tag


  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script type='module' src="../app.js"></script>
</body>

Upvotes: 0

user1171983
user1171983

Reputation:

import axios from 'axios';

Bare module imports won't work in the browser. You need to use relative paths to a file that can be served by your web server (and not simply the NPM package name/a module exported by a package in node_modules and not a served directory), or a toolchain that can use a provided project root to generate the relative paths/pull in code from node_modules into a bundle.

It is saying modules must be on top level to import but it is at the top level from what I can tell

You didn't provide your entire setup, but using the implied hierarchy, I get Uncaught TypeError: Failed to resolve module specifier "axios". Relative references must start with either "/", "./", or "../". in Chrome, which is consistent with the above issue.

Upvotes: 4

Related Questions