当我尝试导入包含模块的目录时,Webpack错误

我正在尝试创建一个小的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运行build (运行 webpack --display-error-details --mode production )时,webpack抛出一个大错误,提示“ Module not找到:错误:无法解析“ my \ project \ dir \ src”中的“ ./端点”

我的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']
    }
};

我可以看到之前曾问过类似的问题,并且列出的解决方案似乎对我不起作用,所以我认为我应该把它发布出来,以防我出现菜鸟错误。如果需要更多信息,请说!抱歉,如果它是一堆文字。谢谢。

qiao799 回答:当我尝试导入包含模块的目录时,Webpack错误

正确的导入应为:

 import endpoint1 from 'endpoint1';

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

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

 import endpoint1 from "./endpoints/endpoint1";
,

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不支持命名导出。这等效于export default class lib ...型导出中的es6 modules

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

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文件。仅在必要时使用它。例如。数据库迁移。

本文链接:https://www.f2er.com/3134928.html

大家都在问