首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Webpack:错误:无法解析'MyCustomPath/‘

Webpack:错误:无法解析'MyCustomPath/‘
EN

Stack Overflow用户
提问于 2020-02-20 00:55:46
回答 1查看 57关注 0票数 0

我的webpack.config.js

代码语言:javascript
运行
复制
module.exports = {
    entry: './app/components/App.js',
    resolve: {
        alias: {
          Base: './app/components/Base',
          Modules: './app/components/Modules',
          Screens: './app/components/Screens',
          Units: './app/components/Units'
        }
    },
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader"
            },
        }
      ]
    }
  };

在App.js中,我尝试这样导入:

代码语言:javascript
运行
复制
import NotifyModal from 'Modules/NotifyModal';
import Preloader from 'Base/Elements/Preloader';

但我得到以下错误:

代码语言:javascript
运行
复制
ERROR in ./app/components/App.js
Module not found: Error: Can't resolve 'Base/Elements/Preloader' in '/home/cpt/Desktop/development/app/components'
 @ ./app/components/App.js 34:0-56 163:29-42

ERROR in ./app/components/App.js
Module not found: Error: Can't resolve 'Modules/NotifyModal' in '/home/cpt/Desktop/development/app/components'
 @ ./app/components/App.js 51:0-46 124:29-36

请告诉我,我做错了什么?我的应用程序中有很多别名,但它们不起作用

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-20 02:00:23

我在使用webpack的alias功能时并不是很成功,它对我来说从来都不起作用。取而代之的是,我使用了这个babel插件:babel-plugin-module-resolver

要使用它,您可以创建一个自定义babel.config.js文件,如下所示:

代码语言:javascript
运行
复制
module.exports = function(api) {
    api.cache(true);

    return {
        presets: [ "@babel/preset-env", "@babel/preset-react"],
        plugins: [
            [
                "module-resolver", 
                {
                   // put your aliases here; I use a tilde (~) to represent
                   // that the folder is aliased, but you don't have to
                    alias: {
                        ~actions: "./src/actions",
                        ~components: "./src/components",
                        ~containers: "./src/containers",
                        ~pages: "./src/pages",
                        ~reducers: "./src/reducers",
                        ~root: "./src/root",
                        ~routes: "./src/routes",
                        ~sagas: "./src/sagas",
                        ~styles: "./src/styles",
                        ~types: "./src/types",
                        ~utils: "./src/utils",
                    },
                },
            ],
            "@babel/plugin-transform-runtime",
            "@babel/plugin-syntax-dynamic-import",
            ["@babel/plugin-proposal-class-properties", { loose: true }],
        ],
    };
};

然后,您可以像这样引用一个别名文件夹:import App from "~components/App" (假设App是一个包含index.js文件的文件夹)。

但是,正如您所看到的,上面的方法非常重复,您必须手动添加别名。所以我创建了这个函数来遍历一个特定的文件夹,并给其中的所有顶层文件夹起别名:

代码语言:javascript
运行
复制
const { readdirSync, statSync } = require("fs");
const { resolve } = require("path");

// read all directories within the path specified below 
// and reduce (loop) through them
const readDirectory = path =>
    readdirSync(path).reduce((acc, folder) => {
        // combine the path with the current folder name
        // for example: "./src/components"
        const dirPath = `${path}${folder}`; 

        // check that the directory (dirPath) exists
        if (statSync(resolve(dirPath)).isDirectory()) { 
            // add the folder as an alias, for example: 
            // "~components": "./src/components" 
            // to the accumulator (an object)
            acc[`~${folder.replace(/[^\w\s]/gi, "")}`] = dirPath;  
        }

        // return the accumulated object of directories
        return acc; 
    }, {});

// read all top-level directories within "./src/"
const alias = readDirectory("./src/");

module.exports = function(api) {
    api.cache(true);

    return {
        presets: [ "@babel/preset-env", "@babel/preset-react"],
        plugins: [
            [
                "module-resolver",
                { alias } // apply aliased folder to module resolver options object
            ],
            "@babel/plugin-transform-runtime",
            "@babel/plugin-syntax-dynamic-import",
            ["@babel/plugin-proposal-class-properties", { loose: true }],
        ],
    };
};

另外,我个人避免为顶级根文件夹(位于src之外的文件夹)设置别名;但是,如果您愿意,可以调整上面的函数以包含一个list folders to read and ignore (因为您不想为node_modules.git文件夹设置别名)。同样,如果您只是在src文件夹中使用别名,则不建议也不需要。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60305491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档