admin管理员组

文章数量:1356360

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.

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.

Share Improve this question asked Apr 28, 2019 at 1:34 PorcupineTitsPorcupineTits 211 gold badge1 silver badge3 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

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.

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.

Unlike Node, by default browser doesn't know where to find the Axios library, just from the string "axios".

You need to make the library be served by the web server and then import it from the correct URL.

import axios from "/path-to-libs/axios/index.js";

Alternatively you can tell the browser where "axios" is, by providing import maps.

<script type="importmap">
  {
    "imports": {
      "axios": "/path-to-libs/axios/index.js"
    }
  }
</script>

Then import axios from "axios"; will work.

<script type="importmap">
  {
    "imports": {
      "axios": "https://cdnjs.cloudflare./ajax/libs/axios/1.7.8/esm/axios.js"
    }
  }
</script>
<script type="module">
  import axios from "axios";
  const r = await axios.get("https://httpbin/user-agent");
  console.log(r.data);
</script>

A quick and dirty way is to use the cdn:

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

put it in your html file above your JavaScript tag


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

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

本文标签: