简体   繁体   English

从React中的node_modules动态导入

[英]Dynamic import from node_modules in react

I want to import a component from node_modules like this. 想像这样从node_modules导入组件。 But it not working. 但它不起作用。

( created project by create-react-app ) (由create-react-app创建的项目)

import React from 'react';
const a = '@sarin/coral-button';
import(a);

This is an error message. 这是一条错误消息。

This is an error message. 这是一条错误消息。

This is an error message. 这是一条错误消息。

and I have tried to config webpackAlias with customize-cra and react-app-rewired like this in 而且我试图用custom -crareact-app- rewired配置webpackAlias像这样

"config-overides.js" but i still got the same error as before. “ config-overides.js”,但我仍然收到与以前相同的错误。

module.exports = override( 
addWebpackAlias({
  ["@sarin/coral-button"]: path.resolve(__dirname, "node_modules/@sarin/coral-button"),
}),

but if i import statically it will working. 但是,如果我静态导入它会工作。

import React from 'react';
import('@sarin/coral-button');

Webpack does not try to find the variables inside your javascript file. Webpack不会尝试在javascript文件中查找变量。 In your case, you have defined some variable a with the path. 在您的情况下,您已使用路径定义了一些变量a。 Then you are using dynamic import. 然后,您正在使用动态导入。 While building, webpack will only perform static analyze. 在构建时,webpack将仅执行静态分析。 It will not try to find the variable a inside your javascript file. 它不会尝试在JavaScript文件中找到变量a。 so the correct way is to specify your path directly inside your dynamic import statement. 因此正确的方法是直接在动态import语句中指定路径。

import(/* webpackChunkName: "user-defined" */'@sarin/coral-button');

From the document of dynamic import is explained 从文件动态导入讲解

Here specifier will be interpreted the same way as in an import declaration (ie, the same strings will work in both places). 这里的说明符的解释方式与导入声明中的解释方式相同(即,相同的字符串将在两个地方都起作用)。 However, while specifier is a string it is not necessarily a string literal; 但是,尽管说明符是字符串,但不一定是字符串文字。 thus code like import( ./language-packs/${navigator.language}.js ) will work—something impossible to accomplish with the usual import declarations. 因此,像import( ./language-packs/${navigator.language}.js - ./language-packs/${navigator.language}.js )这样的代码就可以工作-用常规的导入声明无法完成某些工作。

So, Let's change your code to use template string. 因此,让我们将代码更改为使用模板字符串。

import React from 'react';
const a = '@sarin/coral-button';
import(`${a}`);

I have been tested from the latest create-react-app with below code and it work correctly 我已经通过最新的create-react-app使用以下代码进行了测试,并且可以正常工作

import React from 'react';
import logo from './logo.svg';
import './App.css';

const a = './hello'
import(`${a}`).then(hello => console.log('HELLO', hello.default))

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

and change code style to use async/await it work correctly too. 并更改代码样式以使用异步/等待它也可以正常工作。

import React from 'react';
import logo from './logo.svg';
import './App.css';

(async () => {
  const a = './hello';
  const b = await import(`${a}`);
  console.log(b.default)
})()


function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

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

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