【问题标题】:Webpack is erroring when I attempt to import a directory containing modules当我尝试导入包含模块的目录时,Webpack 出错
【发布时间】:2019-11-08 21:51:37
【问题描述】:

我正在尝试创建一个小型 npm 库,以使与 API 的接口更加整洁。我的文件夹结构如下...

dist/
  index.js
src/
  index.js
  endpoints/
    endpoint1.js
package.json
webpack.config.js

在我的 src/index.js 文件中,我有..

import {endpoint1} from './endpoints'

module.exports = class lib {
 ...
}

当我 npm run build(运行 webpack --display-error-details --mode production)webpack 抛出一个大错误,说 “Module not发现:错误:无法解析“my\project\dir\src”中的“./endpoints”

我的 webpack.config.js 文件目前看起来像...

const path = require('path');

module.exports = {
    mode: 'production',
    entry: path.join(__dirname, '/src/index.js'),
    output: {
        path: path.resolve('dist'),
        filename: 'index.js',
        libraryTarget: 'commonjs2'
    },
    module: {
        rules: [
            {
                test: /.js?$/,
                exclude: /(node_modules)/,
                use: 'babel-loader'
            }
        ]
    },
    resolve: {
        modules: [

            path.resolve(__dirname, 'src/endpoints')
        ],
        extensions: ['.js']
    }
};

我可以看到之前有人问过类似的问题,并且列出的解决方案似乎对我不起作用,所以我想我会发布它以防我犯了新手错误。如果需要更多信息,请说!对不起,如果它是相当多的文字墙。谢谢。

【问题讨论】:

  • 模块名称为“endpoint1”
  • 应该将其发布为答案,乔纳斯·威尔姆斯。我认为这是有效的,因为它解决了他的问题
  • './endpoints' 指的是./endpoints/index.js,因为它是一个目录。您要么想导入'./endpoints/endpoint1',要么创建index.js,然后导出endpoint1
  • 感谢您的快速回复!有没有办法我可以导入包含模块的目录?从目录中显式导入每个模块会有点麻烦...
  • @ToastedToast 我在编辑中提到了它

标签: javascript npm webpack babeljs


【解决方案1】:

正确的导入是:

 import endpoint1 from 'endpoint1';

通过使用resolve.modules,您告诉 Webpack 在该文件夹中查找非相对路径。模块名称为“enpoint1”。

但实际上,您应该只对您在项目中使用的库执行此操作,对于端点,相对导入将是合适的:

 import endpoint1 from "./endpoints/endpoint1";

【讨论】:

  • 我不明白为什么非相对路径应该在那个文件夹中。这个文件夹怎么这么特别?这是可能的,但似乎很奇怪。通常非相对路径指的是node_modules。人们会感到困惑。
  • 同意。别名在这里更合适,或者导入./enpoint/endpoint1。将扩展答案。
【解决方案2】:

import {endpoint1} from './endpoints' 表示: 从文件./endpoints/index.js 导入在该文件中以名称enpoint1 导出的内容。如果您导入目录,则它指的是该目录下的index.js,而不是所有其他文件。它在您的设置中不存在。

{} 中的名称指的是命名导入。这仅适用于es6 modules 风格的导入,例如import {...} from。如果您省略 {},则导入默认值。 CommonJs 风格的导入,如 const {...} = require(''),工作方式不同。 CommonJs 没有命名的导入和导出。它只会从该文件中导入默认值,然后通过对象解构获取一个字段。

您导出的是文件 ./endpoints/enpoint1.js 中未命名(即默认)的内容

由于您使用module.exports =,即CommonJS 样式导出,因此未命名某些内容。 CommonJS 不支持命名导出。这相当于 es6 modules 样式导出中的 export default class lib ...

如果您想在目录下导入许多文件,您可以考虑以下解决方案:

1) 通常会创建单个导入点。你制作了一个index.js 文件。在其中手动导入要导出的目录下的每个文件。然后以名称导出它。像这样:

import a from './a.js';
import b from './b.js';
import c from './c.js';

export { a, b, c };

然后就可以了

2) 在极少数情况下,可能会使用fs.readdirfs.readdirSync 扫描整个目录并在循环中动态地扫描require 文件。仅在必须时使用它。例如。数据库迁移。

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2021-09-06
    相关资源
    最近更新 更多