无法从 npm 包安装访问 Chart.Js 库

问题描述 投票:0回答:1

就上下文而言,我正在构建一个 Web 应用程序,用于记录在某些技能或活动上花费的时间,然后使用 Chart.js 通过条形图将这些数据显示给用户。当我使用 CDNJS 时,我能够成功显示模拟图,但如果可能的话,我想避免使用 CDNJS。我已经通过 npm install 安装了 Chart.js 软件包,并通过验证它是否在 package.json 中来双重检查安装是否成功。

这就是我当前的工作主页:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Main Page</title>
    <!-- Reference Chart.js from cdnjs -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js"></script>
</head>
<body>
    <h1>Main Page</h1>
    <!-- Your main page content here -->

    <!-- Canvas element for the chart -->
    <canvas id="hoursChart" width="400" height="400"></canvas>

    <!-- Button to add logged hours -->
    <button onclick="addLoggedHours()">Add Logged Hours</button>

    <!-- Button to add new skills -->
    <button onclick="addNewSkill()">Add New Skill</button>

    <script>
        //Function to initialize and update the chart
        function updateChart(data) {
            var ctx = document.getElementById('hoursChart').getContext('2d');
            var myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: 'Logged Hours',
                        data: data.hours,
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
        }
        // Sample data for the chart
        var sampleData = {
            labels: ['Skill 1', 'Skill 2', 'Skill 3'],
            hours: [10, 20, 30] // Sample hours logged for each skill
        }

        // Call updateChart function with sample data
        updateChart(sampleData);

        // Need to add function that adds new logged hours

        // Need to add function that adds a new skill to graph
    </script>
</body>
</html>

连同我正在工作的 app.js(仅包括相关部分...如果需要,可以包括完整的 app.js 文件):

const express = require('express');
const exphbs = require('express-handlebars');
const path = require('path');

const app = express();

app.engine('.hbs', exphbs.engine({
    extname: '.hbs',
    defaultLayout: 'main', // Main layout file
    layoutsDir: path.join(__dirname, '..', 'frontend', 'views', 'layouts'),
    partialsDir: path.join(__dirname, '..', 'frontend', 'views', 'partials')
}));
app.set('view engine', '.hbs');
app.set('views', path.join(__dirname, '..', 'frontend', 'views'));

// Serve static files (CSS, Javascript, etc.)
app.use(express.static(path.join(__dirname, '..', 'frontend')));

// Define Routes
app.get('/main', (req,res) => {
    res.render('mainpage');
});

但我想知道是否有办法避免使用 CDNJS 并能够直接从下载的 node_modules 访问 Chart.js 库。

我已经对 HTML 文件尝试过类似的操作:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Main Page</title>
    <!-- Reference Chart.js from node_modules -->
    <script src="/node_modules/chart.js/dist/chart.umd.js">

在 app.js 服务器文件中添加以下内容:

app.use(express.static(path.join(__dirname, '..', 'node_modules')));

但是,这不会显示图表,而是在控制台中给出这些错误:

"GET http://localhost:3000/node_modules/chart.js/dist/chart.umd.js net::ERR_ABORTED 404 (Not Found)"
"Refused to execute script from 'http://localhost:3000/node_modules/chart.js/dist/chart.umd.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled."
"main:45 Uncaught ReferenceError: Chart is not defined"

我已经使用控制台日志多次检查了文件路径,并咨询 ChatGpt 进行错误修复,以确保它们是正确的。甚至尝试为其提供绝对路径,而不是 VScode 建议的相对路径。

有一个简单的解决办法吗?或者我应该默认使用 CDNJS 参考并放弃尝试使用我从 npm 下载的 Chart.js 本地包。

作者注: 抱歉,如果我没有正确描述事物或误解了某些概念。我对全栈 Web 开发还比较陌生,所以别着急,哈哈。

javascript node.js express npm chart.js
1个回答
0
投票

有一个简单的解决办法吗?或者我应该默认使用 CDNJS 参考并放弃尝试使用我从 npm 下载的 Chart.js 本地包?

您不应该将

node_module
服务器设置为静态,因为它们特定于 NodeJS 环境而不是浏览器环境

而是下载

chart.js
文件并将其作为静态文件使用

这样使用

<script src="/frontend/static/js/chart.4.4.1.js"></script>

我假设您使用的是静态文件夹,也不要忘记在文件名中添加版本号

© www.soinside.com 2019 - 2024. All rights reserved.