从file.js导入所有变量,并带有“import'。/ file.js'”召唤

问题描述 投票:2回答:3

我正在使用import函数,我希望使用类似于css的导入,我的意思是“import'./file.css'”然后所有的css属性都在文件中扩散。我已经尝试过与ReactJS相同但它失败了。

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

Here my sandbox

这是相关代码:

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

从“./sample”导入“./export.js”导入样本; import“./ 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}

我想知道如何制作类似的东西。任何提示都会很棒,

谢谢

javascript reactjs
3个回答
2
投票

沙盒中的违规代码是:import "./exported.js";

混淆的一个原因是您正在使用Create React App,它隐藏了webpack魔法,允许您将CSS文件导入为import "./styles.css";。这不是模块导出和导入的工作方式。我建议阅读关于exploringjs.com的导出和导入细节的部分

你正在做的事实上是一个空的导入,即你没有导入任何东西,只是执行该文件。

空导入:仅加载模块,不导入任何内容。程序中的第一个这样的导入执行模块的主体。 import'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

2
投票

你需要做import defaultExport from 'moduleName';所以你可以在你的代码中使用defaultExport

执行import 'moduleName';只会运行模块中的代码,但不会导入任何内容(有关详细信息,请参阅MDN

在你的沙盒中,做import sample from 'sample.js';会做到这一点。


2
投票

您的代码中的问题会导致导入中断,但不包括您的css文件,问题是导入export.js和sample.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";

这里完整的样本Code Sample

有关import statement更多信息:import解构赋值声明:destructuring assignment

最好的祝福。

© www.soinside.com 2019 - 2024. All rights reserved.