簡體   English   中英

通過“ import'./file.js'”從file.js導入所有變量

[英]import all variables from a file.js with an “ import './file.js' ” summoning

我正在使用導入功能,我希望使用類似css的導入,我的意思是“ import'./file.css'”,然后所有css屬性都分散在文件中。 我已經用ReactJS嘗試了同樣的方法,但是失敗了。

我的期望是模仿js文件的css導入,但是它不起作用。

這是我的沙盒

以下是相關代碼:

import React from "react";
import ReactDOM from "react-dom";

來自“ ./sample”導入“ ./exported.js”的impoprt示例; 導入“ ./styles.css”;

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {sample[2]}
      {text1}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

當不使用星號導入時,我在一行出現錯誤:

  {text1}

我想知道如何制作類似的東西。 任何提示都會很棒,

謝謝

您需要import defaultExport from 'moduleName'; 因此您可以在代碼中使用defaultExport

正在import 'moduleName'; 只會運行模塊中的代碼,而不會導入任何內容(有關詳細信息,請參見MDN

在您的沙箱中, import sample from 'sample.js'; 會做到的。

您的沙箱中有問題的代碼是: import "./exported.js";

造成混亂的原因之一是您正在使用Create React App,它隱藏了webpack的魔力,使您可以將CSS文件import "./styles.css";import "./styles.css"; 這不是模塊導出和導入的方式。 我建議您閱讀exploringjs.com上有關導出和導入詳細信息的部分

實際上,您正在執行的操作是一個空導入 ,即您不導入任何內容,而只是執行文件。

空導入:僅加載模塊,不導入任何內容。 程序中的第一個此類導入將執行模塊的主體。
導入'src / my_lib';

簡而言之,這里有各種導入方式。

假設:您的./exported.js文件具有以下導出:

// some other code
export { text1, text2 };
export default config;

然后您可以將它們導入各種格式

// import only the default export
import config from './exported.js';
// This only imports the export qualified with default, it ignores others 
// i.e. 
console.log(config); //works
console.log(text1); // fails
console.log(text2); // fails

// import everything the module exports, but as a namespace
import * as myLib from './exported.js';
// usage: all named exports are properties of the myLib object
console.log(myLib.text1); // works
console.log(myLib.text2); // works
console.log(myLib.config); // should not work, unless you have also exported config as a named export

// import only what you need
  import { text1, text2 } from './exported.js';
  console.log(text1); // works
  console.log(text2); // works

// you can also rename them
  import { default as x, text1 as a, text2 as b } from './exported.js';
  console.log(x); // works --> config
  console.log(a); // works --> text1
  console.log(b); // works --> text2

您的代碼中的問題導致導入中斷,該導入不允許包含您的css文件,問題是導入export.jssample.js ,必須使用正確的Destructuring進行導入,例如:

import React from "react";
import ReactDOM from "react-dom";
import { text1, text2 } from "./exported.js";
import sample from "./sample.js";
import "./styles.css";

在這里完成示例代碼Sample

有關import語句更多信息: 進口 解構賦值語句: 解構賦值

最好的祝福。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM