【问题标题】:Problem using npm of chart.js in django Project在 django 项目中使用 chart.js 的 npm 的问题
【发布时间】:2022-11-05 05:09:43
【问题描述】:

我尝试在我的 Django 项目中使用 Chart.js,当我使用 NPM 包时它不起作用但是当我使用 CDN 时它完美地工作

char.js 版本 3.9.1

这是我项目中的 index.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
{#    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>#}
    <script type="application/json" src="/node_modules/chart.js/dist/chart.js"></script>
</head>
<body>

<canvas id="myChart" width="400" height="400"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});
</script>


</body>
</html>

我在浏览器中的控制台错误是:

(index):17 Uncaught ReferenceError: Chart is not defined
    at (index):17:17

我试图在我的脚本中使用 chart.min.js 但没有工作。 我也尝试了以前版本的 charj.js,但仍然无法正常工作。 我还在 CDN 上复制代码并将其放在本地项目中,但仍然无法正常工作。

【问题讨论】:

    标签: javascript django npm chart.js


    【解决方案1】:

    问题是 Django 根据您在 Python 视图中的上下文对象中声明的内容来呈现 html。 Django 对 NPM、NodeJS 和 node_modules 文件夹一无所知。

    通常,当您使用 npm 安装软件包时,是因为您在 NodeJS 项目中使用它们,最终将转换为没有依赖关系的 vanilla JS 文件,以进行托管。

    这就是为什么使用 npm 安装 Chart.js 它不起作用的原因,因为它将存储在 node_modules 文件夹中,而 Django 不知道如何处理它。但是当你使用 cdn 时,你几乎是将依赖嵌入到 html 中,现在它可以在声明后在所有 JS 脚本中引用。

    我希望解释对你有所帮助,如果有什么你认为没有很好解释的地方,请告诉我。

    【讨论】:

      【解决方案2】:

      必须使用静态路径,以便 django 可以服务器 js 文件 项目名称 应用名称 静止的 js css 图像

      【讨论】:

        猜你喜欢
        • 2017-04-02
        • 1970-01-01
        • 2022-12-04
        • 2016-10-26
        • 1970-01-01
        • 2021-09-09
        • 1970-01-01
        • 1970-01-01
        • 2021-01-05
        相关资源
        最近更新 更多