我目前正在学习使用nodejs,express作为franework,handlebar作为模板引擎。
PS:这是chartjs教程中使用parcel的部分。
当我尝试用express(node src/app.js)做同样的事情时,我得到一个错误Failed to resolve module specifier“chart.js/auto”
我注意到有几次我无法在外部JS文件中导入模块。有没有一种方法可以在外部的js文件中导入模块,或者是express特别是无法相同的。
我已经用npm安装了chartjs。我有一个页面index.hbs
<!doctype html>
<html lang="en">
<head>
<title>Chart.js example</title>
</head>
<body>
<div style="width: 800px;"><canvas id="acquisitions"></canvas></div>
<script type="module" src="./js/acquisitions.js"></script>
</body>
</html>
和acquisitions.js
import Chart from 'chart.js/auto'
(async function() {
const data = [
{ year: 2010, count: 10 },
{ year: 2011, count: 20 },
{ year: 2012, count: 15 },
{ year: 2013, count: 25 },
{ year: 2014, count: 22 },
{ year: 2015, count: 30 },
{ year: 2016, count: 28 },
];
new Chart(
document.getElementById('acquisitions'),
{
type: 'bar',
data: {
labels: data.map(row => row.year),
datasets: [
{
label: 'Acquisitions by year',
data: data.map(row => row.count)
}
]
}
}
);
})();
1条答案
按热度按时间yrdbyhpb1#
可以使用导入Map导入模块
Import maps允许开发人员在导入模块时在模块说明符中指定几乎任何他们想要的文本;Map提供了一个相应的值,当模块URL被解析时,该值将替换文本。
让我们看一个例子,我将使用HTML文件来演示。使用任何模板引擎都是一样的。
目录结构:
app.js
:public/index.html
:public/js/acquisitions.js
:chart.js
使用@kurkle/color
作为其依赖项,因此我们必须将其添加到导入Map中。chart.js
将使用import '@kurkle/color'
语句导入它。启动服务器并访问
http://localhost:3000
端点,结果: