[英]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.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";
在这里完成示例代码Sample 。
有关import语句更多信息: 进口 解构赋值语句: 解构赋值 。
最好的祝福。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.