如何使用webpack将相对路径别名为自定义路径?

Jid*_*ide 8 webpack

一个项目使用模块A.

该模块需要具有本地路径,例如require('./otherModule').

如何使webpack从另一个目录解析此路径,如果它不存在则回退到正常解析?

Jid*_*ide 8

也可以像这样使用NormalModuleReplacementPlugin:

  plugins: [
    new webpack.NormalModuleReplacementPlugin(/^\.\/ReactCompositeComponent$/, 'ReactCompositeComponent'),
    new webpack.NormalModuleReplacementPlugin(/^\.\/ReactDOMComponent$/, 'ReactDOMComponent')
  ]
Run Code Online (Sandbox Code Playgroud)


Joh*_*ald 7

没有简单的方法可以对相关require()语句进行别名require('./otherModule').,我不建议这样做.它打破了文件路径的基本概念,可能会混淆其他程序员.

根相对路径(推荐)

您可以使用"根相对"路径.这些是以a开头的路径/.然后你可以写这样的require语句require("/app/controller/otherModule.js").你只需要告诉webpack你的root位置:

// webpack.config.js

module.exports = {
    ...
    resolve: {
        root: "/absolute/path/to/your/folder"
    }
    ...
};
Run Code Online (Sandbox Code Playgroud)

您还可以提供一系列路径root.

解析器插件(不推荐)

但是,如果您确实需要为这些路径添加别名,则可以挂钩webpack的解析机制.Webpack为插件提供了广泛的API来改变其行为.重写所有相对路径的插件将如下所示:

// webpack.config.js

var myWebpackPlugin = {
    apply: function (compiler) {
        compiler.resolvers.normal.apply(myResolverPlugin)
    }
};

var myResolverPlugin = {
    apply: function (resolver) {
        resolver.plugin("resolve", function (context, request) {
            if (request.path[0] === ".") {
                request.path = path.resolve(__dirname,
                    "whatever", "you", "like", request.path);
            }
        });
    }
}

module.exports = {
    ...
    plugins: [
        myWebpackPlugin
    ]
};
Run Code Online (Sandbox Code Playgroud)