首页 > 解决方案 > 导入/导出 JavaScript

问题描述

我在一个文件中有以下课程

src/ui.js

export default class UI {

    static generateUI(restaurant) {
        const container = document.getElementById('container')

        const addButton = document.createElement('button')
        addButton.setAttribute('type', 'button')
        addButton.innerText = "Add"
        addButton.setAttribute('id', restaurant.id)
        addButton.setAttribute('class', 'addButton')
        addButton.addEventListener("click", function() {
            fetch('http://localhost:3000/add', {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    id: restaurant.id 
                })
            })
            .then(resp => resp.json())
            .then(confirmation => UI.showAddSuccess(confirmation))
        })

        const name = document.createElement('h2')
        name.innerText = restaurant.name

        const ul = document.createElement('ul')
        ul.setAttribute('class', 'dishList')

        restaurant.foods.forEach(food => {
            const dish = document.createElement('li')
            dish.innerText = food.dish 
            const button = document.createElement('button')
            button.setAttribute('id', food.id)
            button.setAttribute('class', 'deleteButton')
            button.setAttribute('type', 'button')
            button.innerText = "Delete"
            button.addEventListener("click", function() {
            fetch('http://localhost:3000/delete', {
                method: "DELETE",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    id: food.id,
                })
            })
            .then(resp => resp.json())
            .then(confirmation => UI.showDeleteSuccess(confirmation))
            })
            dish.append(button)
            ul.append(dish)
        })

        const post = document.createElement('div')
        post.setAttribute('class', 'post')
        post.append(addButton, name, ul)
        container.append(post)
    }

    static showDeleteSuccess(confirmation) {
        const showMessage = document.getElementById('delete-success')
        showMessage.innerText = confirmation.message
        setTimeout(function() {
            window.location.reload(1)
        }, 1500
        )
    }

    static showAddSuccess(confirmation) {
        const showMessage = document.getElementById('add-success')
        showMessage.innerText = confirmation.message
        setTimeout(function() {
            window.location.reload(1)
        }, 800
        )
    }

    static toggleDarkMode() {
        const background = document.getElementById('body')
        const posts = document.querySelectorAll('.post')

       const toggleButton = document.getElementById('toogle-dark-mode')
       toggleButton.className = 'border-4, border-light-blue-500, border-solid'
        
        toggleButton.addEventListener("click", function() {
            background.classList.toggle('darkMode');
            posts.classList.toggle('darkModePosts')
            })
    }

    static consolelog() {
        console.log("hello")
    }
}

我正在尝试将其导入另一个

src/index.js

从 './ui.js' 导入 UI

class API {
    constructor() {
        fetch('http://localhost:3000/')
        .then(res => res.json())
        .then(restaurants => {
            restaurants.map(restaurant => {
                UI.generateUI(restaurant)
            })
        })
    }
}

api = new API

UI.toggleDarkMode()

当我这样做时,我没有在浏览器中看到我期望的结果。然而,当它们都在同一个文件中时,它可以工作。

浏览器告诉我Uncaught SyntaxError: Cannot use import statement outside a module

我尝试使用 require 语法,这给了我错误Uncaught ReferenceError: require is not defined at index.js:1

标签: javascript

解决方案


您需要检查您正在使用的环境,

您用于导出类的语法是 ES6 模块语法。如果您从 nodejs 环境调用它,它会抛出错误,因为 nodejs 使用 commonjs 模块语法。

在 commonjs 模块语法中

//for exporting
module.exports = {
   // names of variables, classes, functions goes here
}

//for importing
const UI = require('path/to/your/module')

您还需要确保,如果导出是命名导出或默认导出,则导入语法将分别改变。

谢谢


推荐阅读