如何从 node_module 的子目录导入?

How to import from subdirectory from a node_module?

我正在使用 create-react-app 并且我有一行内容为:

import createHistory from 'history/lib/createBrowserHistory'

但这不起作用并且会引发错误:

Error in ./src/deps/history.js.
Module not found: 'history/lib/createBrowserHistory' 
in /home/aurimus/Apps/projects/my-project/src/deps

create-react-app 是否明确不支持此功能?我该如何避免这种情况?

***更新***

修正lib的url后(使用的是过时的教程),我仍然没有导入任何东西,createBrowserHistoryundefined

我正在使用附加文件来抽象​​ import:

里面deps/history.js

import createBrowserHistory from 'history/createBrowserHistory.js'
export default createBrowserHistory

里面index.js

import history from './deps/history';
history.listen(render); // history is undefined

我做错了什么吗?

Is this specifically not supported by create-react-app?

不,这与create-react-app无关。

How do I circumvent this?

该错误告诉您确切的问题所在:

Module not found: 'history/lib/createBrowserHistory'

这意味着 history/lib/createBrowserHistory 不存在,即您使用了错误的路径。

我安装了history,查看了包内容,发现文件createBrowserHistory位于包的根目录下(实际上没有lib/目录) .这意味着您要导入 history/createBrowserHistory.

来自history docs

Using npm:

$ npm install --save history
Then with a module bundler like webpack, use as you would anything else:

// using ES6 modules
import createHistory from 'history/createBrowserHistory'

// using CommonJS modules
var createHistory = require('history').createBrowserHistory

我最终的解决方案要归功于 Felix:

deps/history.js

import createBrowserHistory from 'history/createBrowserHistory.js'
export default createBrowserHistory()

然后在index.js

import history from './deps/history';
...
...
history.listen(render);