gpt4 book ai didi

javascript - 当我尝试导入包含模块的目录时 Webpack 出错

转载 作者:行者123 更新时间:2023-11-30 13:48:36 25 4
gpt4 key购买 nike

我正在尝试创建一个小型 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']
}
};

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

最佳答案

正确的导入应该是:

 import endpoint1 from 'endpoint1';

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

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

 import endpoint1 from "./endpoints/endpoint1";

关于javascript - 当我尝试导入包含模块的目录时 Webpack 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58774209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com