gpt4 book ai didi

javascript - 将外部js文件导入到另一个外部js文件中

转载 作者:行者123 更新时间:2023-12-03 00:18:31 25 4
gpt4 key购买 nike

在我的 ASP.Net Core MVC 应用程序中,我有几个页面的单独 .js 文件,它们包含正常的验证和客户端逻辑。

我必须在一个通用的 util.js 文件中放置一些方法,并且该文件方法将在其他 js 文件之间共享。

但我无法将此 util.js 的引用添加到其他外部 js 文件中。

我尝试了几种方法

例如我的 util.js

export function ShowAlert(val) {
alert(val);
}

与另一个带有 import 语句的 js 文件 (MyApp.js) 相比

import { ShowAlert } from './util'

function Info() {
var F = document.getElementsByName('txtFName')[0].value
var L = document.getElementsByName('txtLName')[0].value
if (F.length > 0 && L.length > 0)
ShowAlert(F + ' ' + L)
else
ShowAlert('Fields Required');
}

但它在导入语句行中给出错误

Unexpected token {

比我尝试过babel工具来获取浏览器兼容的js,这是

//import { ShowAlert } from './util'
var _util = require('./util');

function Info() {
var F = document.getElementsByName('txtFName')[0].value
var L = document.getElementsByName('txtLName')[0].value
if (F.length > 0 && L.length > 0)
_util.ShowAlert(F + ' ' + L)
else
_util.ShowAlert('Fields Required');
}

现在它说 require is not Define ,所以在网上搜索了几篇文章后,我找到了一个解决方案,并在 MyApp.js 之前包含了 require.js

<script src="./require.js" type="text/javascript"></script>
<script src="./MyApp.js" type="text/javascript"></script>

但是还是报错

Module name "util" has not been loaded yet for context: _. Use require([])

如何将一个 js 文件引用到另一个文件以及为什么 import 在这里给出错误?

更新1

Util.js

export default function ShowAlert(val) {
alert(val);}

MyApp.js

import { ShowAlert } from './util';
//var _util = require('./util');
function Info() {
var F = document.getElementsByName('txtFName')[0].value
var L = document.getElementsByName('txtLName')[0].value
if (F.length > 0 && L.length > 0)
ShowAlert(F + ' ' + L)
else
ShowAlert('Fields Required');
}

最佳答案

要在客户端使用 JavaScript 模块,您需要:

例如:

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<title>Test</title>
<h1>Test</h1>
<script type="module" src="main.js"></script>

main.js

import {sum} from './module.js';

const value = sum(1,2);
const node = document.createTextNode(value);
document.body.appendChild(node);

module.js

function sum(a,b) {
return a + b;
}

export { sum }

关于javascript - 将外部js文件导入到另一个外部js文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54435718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com