javascript - 如何在 js 中使用外部 js 文件?
问题描述
我想缩短我的 js 中的行数。我在文件顶部有我的 json。我想将其存储在单独的文件中。在 php 中,您只需执行一个包含语句,除了 js 是否有类似的东西?
解决方案
您可以通过多种方式在 js 文件之间进行通信。在es5中
//FOR EXPORT use module.exports
eg. module.exports= any content(function, object, array).
//FOR IMPORT use require method
eg. const xyz = require('.path_to_your_file) //.js extension is optional
//now exported content will be available in xyz.
在es6 中我们命名为 export和default export
// FOR **default export** use export default
// eg. export default (any content [array,object,function])
// NOTE:- you can have only one default export in a file
// FOR named export use export
// eg. export (any content [array,object,function])
// NOTE:- you can have multiple export in a file
///####################################
// FOR importing **default exported** content use following syntax
// import ABC from 'source file';
//now exported content will be available in ABC.
// FOR importing **named exported** content use following syntax
// import {exported_name} from 'source file'; // see object destruct in es6 for detail
// as we can have multiple named export we can import multiple content using comma separated syntax and using.
// import { export1,export2} from 'source file';
您也可以将所有命名的导出组合在单个导入名称中,如下所示。
//import * as ABC from 'source file';
在这里,所有命名的导出都将在 ABC 对象中可用,您可以通过点或括号表示法访问。
推荐阅读
- flutter - 如何在 Flutter 中创建动态 ListView?
- python - AttributeError:模块“asyncio”没有属性“_get_running_loop”
- python - 将 np.tril 和 np.triu 堆叠在一起
- c++ - 可变参数模板折叠程序在 gcc9 中失败
- php - 我怎样才能使ajax安全?
- brightway - 与明威不同单位交流
- listview - Xamarin:具有回收元素和动态行高的 Listview
- c# - 如何通过 AutoMapper 实现具有通用 Queue 类型属性的对象映射
- sql - 使用 sql 查询读取 CSV 数据
- regex - 使用 sed 作为通用替换器