问题描述
能否请您解释一下使用node_modules文件夹中的导入/请求库的思想.
Can you please explain the ideology of using import/require libraries from node_modules folder.
我只想在我的简单项目中使用 konva.js
,将 node.js
用作配置了实时服务器扩展的后端.
I just want to use konva.js
in my simple project, using node.js
as a back end with live-server extension configured.
如果我将其正确地导入到HTML文件中
If I import it right into HTML file like this
<script src="https://unpkg.com/konva@4.0.0/konva.min.js"></script>
<script> /*using konva library here or *.js*/</script>
一切正常
据我了解,此URL会将整个 konva.min.js
导入我的HTML文件中
Everything works
As I understood, this URL imports whole konva.min.js
right into my HTML file
如果我将 konva.js
文件从/node_modules
包复制到我的/src
文件夹
If I copy konva.js
file from /node_modules
package into my /src
folder
并在我的HTML中使用这样的代码
And use code like this in my HTML
<script src="konva.min.js"></script>
<script src="script.js"></script>
我可以访问script.js中的konva库
I have access to konva library in script.js
在服务器端脚本中,由node.js调用,我使用了这样的语句来访问node_modules中的包
In server-side scripts, invoked by node.js I used statement like this to access packages in node_modules
var liveserver = require("live-server");
P.S.为什么在这里不导入工作?Node.js没有导入说明?
P.S. Why doesn't import work here? Node.js doesn't have import instructions?
但是主要的问题是如何在客户端脚本上使用相同的require()/import语法,而不使用< script>
标记导入库?
But the main question is how to use the same syntax of require()/ import on client-side scripts and not to use <script>
tags to import libraries?
import konva from 'konva';
/* js code next*/
OR
var konva = require('konva');
/* js code next*/
我需要使用任务管理器吗?我应该怎么办?在每个 .js
文件中搜索依赖项,并使用任务将这些依赖项直接导入到项目文件夹中?但是,例如,对于gulp,我发现了不同的库来格式化代码,但是找不到所需的库来导入依赖项
I need to use task managers? What should I do? Search for dependencies in each .js
file and use tasks to import these dependencies right into project folder? But, for example, for gulp I found different libraries to format code, but can't find needed one to import dependencies
推荐答案
Node.js是服务器端运行时环境,您需要在客户端/浏览器端使用node_modules库.
Node.js is a server-side runtime environment, what you need is to use the node_modules libraries on the client/browser side.
它将捆绑您所需的文件,并导入到一个js文件中,以便在脚本标签中使用.
It will bundle you require and import into a single js file for use in a script tag.
在客户端使用导入
<script type="module">
import {addTextToBody} from './utils.mjs';
addTextToBody('Modules are pretty cool.');
</script>
您需要的只是script元素上的type = module,浏览器会将内联脚本或外部脚本视为ECMAScript模块
All you need is type=module on the script element, and the browser will treat the inline or external script as an ECMAScript module
// utils.mjs
export function addTextToBody(text) {
const div = document.createElement('div');
div.textContent = text;
document.body.appendChild(div);
}
这些是一些很棒的文章,可以使您更好地理解:
These are some great articles to get a better understanding of this :
这篇关于如何从node_modules导入JS库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!