简体   繁体   English

如何使用 webpack 导入整个 js 文件?

[英]How i can import an entire js file with webpack?

I want to import my file functions.js in my file index.js and use variables and functions are in functions.js.我想在我的文件 index.js 中导入我的文件 functions.js,并在 functions.js 中使用变量和函数。

For ex: I have an variable x in my file functions.js.例如:我的文件 functions.js 中有一个变量 x。 I import functions.js like "import './functions.js';"我像“import './functions.js';”一样导入functions.js in my index.js.在我的 index.js 中。 The path is correct for sure(they are in the same directory).路径肯定是正确的(它们在同一个目录中)。 But when i try to use x, i have this next error -> "index.js:01 Uncaught ReferenceError: x is not defined"但是当我尝试使用 x 时,我遇到了下一个错误 ->“index.js:01 Uncaught ReferenceError: x is not defined”

functions.js export var x = 0;函数export var x = 0;

index.js index.js

import './functions.js';
console.log(x);

Thanks: :)谢谢: :)

The point of modules is to get away from this business of sharing everything in a single scope (the global scope, by default in non-module scripts).模块的意义在于摆脱在单个 scope(全局 scope,默认情况下在非模块脚本中)中共享所有内容的业务。 If you want to do that, don't use modules, use non-module scripts.如果你想这样做,不要使用模块,使用非模块脚本。

Modules are defined in terms of模块定义为

  • What they provide ( export )他们提供什么( export
  • What they expect ( import )他们的期望( import

In general, you're best off making those relationships explicit:一般来说,你最好明确这些关系:

import { x } from "./fonctions.js";
// ...use `x`...

That assumes x is a named export :假设x是一个命名的 export

export const x = /*...*/;
// or
export function x() {
    // ...
};
// etc.

The closest thing to an "import everything from X" construct in JavaScript modules is a module namespace object import, which looks like this: JavaScript 模块中最接近“从 X 导入所有内容”构造的是模块命名空间 object导入,如下所示:

import * as fonctions from "./fonctions.js";

You'd then use fonctions.x to refer to x .然后,您将使用fonctions.x来引用x But , x still has to be exported from fonctions.js (as above).但是x仍然必须从fonctions.js中导出(如上)。 Anything declared in a module that isn't explicitly exported is private to that module, and so it doesn't show up on the module namespace object.在模块中声明的任何显式导出的内容都是该模块私有的,因此它不会显示在模块命名空间 object 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM