如何从文件中获取JavaScript的导入路径

huangapple go评论66阅读模式
英文:

how to get path for import of javascript from file

问题

我有一个文件,其中定义了目录的绝对路径。

Ex : script=/absolutepath/scripts
utility=/absolutepath/utility

我想在其他JavaScript文件中使用 "script"/"utility" 而不是绝对路径。我该如何做?

我想要的是:

import random from "script/random.js"
而不是

import random from "/absolutepath/scripts/random.js"

PS:我正在使用不支持Node模块的k6负载生成框架。

英文:

I have a file where i defined the absolute path of directory.

Ex : script=/absolutepath/scripts
utility=/absolutepath/utility

I want to use "script"/"utility" instead of absolute path in other javascript files.How i can do this.

What i want :

import random from "script/random.js"

instead of

import random from "/absolutepath/scripts/random.js"

PS :I am using k6 load generating framework which doesn't support node modules.

答案1

得分: 1

您目前无法在k6 v0.26.0中执行此操作。

像这样的导入路径被保留供内部k6模块使用(例如 k6/http)和“魔法”远程导入URL(例如 import from github.com/loadimpact/k6/samples/thresholds_readme_example.js 而不是 https://raw.githubusercontent.com/loadimpact/k6/master/samples/thresholds_readme_example.js,我们正在尝试轻轻地不鼓励这样做)。您无法定义自己的导入路径,必须在导入您自己的JS文件时使用相对路径或绝对路径。

英文:

You currently can't do that in k6 v0.26.0.

Import paths like that are reserved for internal k6 modules (e.g. k6/http) and "magic" remote import URLs (e.g. import from github.com/loadimpact/k6/samples/thresholds_readme_example.js instead of https://raw.githubusercontent.com/loadimpact/k6/master/samples/thresholds_readme_example.js, and we're trying to softly discourage this). You can't define your own, you either have to use relative paths or absolute paths when importing your own JS files.

答案2

得分: 0

你可以尝试使用 importmaps

在你的 index.html 中:

<html lang="en">

<head>
    <script type="importmaps">
        {
            "imports": {
                "random": "/absolutePath/scripts/random.js"
            }
        }
    </script>
    <script type="module" src="app.js"></script>
</head>

</html>

现在你可以从任何地方导入你的模块:

import random from 'random'
英文:

You could try using importmaps.

Inside your index.html:

&lt;html lang=&quot;en&quot;&gt;

&lt;head&gt;
    &lt;script type=&quot;importmaps&quot;&gt;
        {
            &quot;imports&quot;: {
                &quot;random&quot;: &quot;/absolutePath/scripts/random.js&quot;
        }
    }
    &lt;/script&gt;
    &lt;script type=&quot;module&quot; src=&quot;app.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;/html&gt;

You can now import your module from ANYWHERE

import random from &#39;random&#39;

huangapple
  • 本文由 发表于 2020年1月6日 20:49:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定