个性化阅读
专注于IT技术分析

当导入有模块的目录时,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 {
 ...
}

当使用webpack构建项目时,抛出错误:Module not found: Error: Can’t resolve ‘./endpoints’ in ‘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']
    }
};

分析和解决问题

正确的导入方式如下:

import endpoint1 from 'endpoint1';

通过使用resolve.modules,你可以设置让webpack在那个文件夹中查找非相对路径,模块名为“enpoint1”。

不过,使用库导入会更合适,这样可以在整个项目中使用,一个相对的导入会更合适,如下:

import endpoint1 from "./endpoints/endpoint1";
赞(0)
未经允许不得转载:srcmini » 当导入有模块的目录时,webpack出错,如何解决?

评论 抢沙发

评论前必须登录!