【问题标题】:can't import side effects in typescript无法在打字稿中导入副作用
【发布时间】:2020-08-15 02:55:25
【问题描述】:

我有以下路由代码(Routes.js):

export default (props) => {
    import(`../styles/${props.site}/theme.css`);

  return (
    <div>
      <Menu />
      <Switch>
        <Route
          exact path="/"
          render={({ staticContext, match }) => {
            const site = staticContext
              ? staticContext.site
              : location.hostname.split(".")[0]
            return <UniversalComponent site={site} match={match} page="core/ToBeDeleted_Homepage" />
          }}
        />
...
...

首先,我导入 css 文件:

"导入(../styles/${props.site}/theme.css);"

这里使用了导入副作用,因此这与将静态工作并在 ${props.site} 变量可用时导入的应用程序绑定。

然后,我使用“return(~~~)”中的所有内容来渲染应用程序

如果上面的代码写在 .js 文件中,这将有效。 但是,这在打字稿(.tsx 文件)中不起作用。

我收到以下错误,因为 .tsx 文件中有非常相似的代码:

[FLUSH CHUNKS]: Unable to find styles/localhost-theme-css in Webpack chunks. Please check usage of Babel plugin.
(node:28539) UnhandledPromiseRejectionWarning: Error: Cannot find module './undefined/theme.css'

看起来它只是在完成导入之前返回......所以这意味着对于打字稿,它不能静态工作,因为它会在 ${props.site} 变量不可用时尝试导入 ${props.site} 并且返回错误。

我该如何解决这个问题?

我的 tsconfig.json:

{
  "compilerOptions": {
    "target": "ESNext", 
    "module": "ESNext", 
    "allowJs": true,    
    "jsx": "react",     
    "sourceMap": true, 
    "outDir": "dist", 
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    ".vscode"
  ]
}

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    您可以使用require 代替import(因为import 只能发生在顶级)。还要考虑将逻辑移到组件之外。

    const importStuff = (site) => {
       if (!site) return;
    
       require(`../styles/${site}/theme.css`);
    };
    

    然后简单地在组件内部:

    export default (props) => {
       importStuff(props.site);
    
       return (...);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 2021-11-11
      • 2017-02-28
      • 2022-01-20
      • 1970-01-01
      • 2021-08-14
      • 2021-08-31
      • 2021-11-07
      相关资源
      最近更新 更多