使用webpack解析需求路径 [英] Resolving require paths with webpack

查看:158
本文介绍了使用webpack解析需求路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然对如何使用webpack解析模块路径感到困惑。现在我写道:

I'm still confused how to resolve module paths with webpack. Now I write:

myfile = require('../../mydir/myfile.js') 

但我想写

myfile = require('mydir/myfile.js') 

我在想什么 resolve.alias 可能有所帮助,因为我看到使用 {的类似示例xyz:/ some / dir} 作为别名然后我可以 require(xyz / file.js)

I was thinking that resolve.alias may help since I see a similar example using { xyz: "/some/dir" } as alias then I can require("xyz/file.js").

但如果我将别名设置为 {mydir:'/ absolute / path / mydir'} require ('mydir / myfile.js')将无效。

But if I set my alias to { mydir: '/absolute/path/mydir' }, require('mydir/myfile.js') won't work.

我感到愚蠢,因为我已多次阅读该文档而且我觉得我错过了什么。
避免用 ../../ 等编写所有相对要求的正确方法是什么?

I feel dumb because I've read the doc many times and I feel I'm missing something. What is the right way to avoid writing all the relative requires with ../../ etc?

推荐答案

Webpack> 2.0



参见 wtk的回答

更直接的方法是使用resolve.root。

A more straightforward way to do this would be to use resolve.root.

http://webpack.github.io/docs/configuration.html#resolve-root

resolve.root

包含模块的目录(绝对路径)。也可以是一系列目录。此设置应用于将单个目录添加到搜索路径。

The directory (absolute path) that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.

在您的情况下:

var path = require('path');

// ...

  resolve: {
    root: path.resolve('./mydir'),
    extensions: ['', '.js']
  }



消费模块



consuming module

require('myfile')

require('myfile.js')

另见: http:/ /webpack.github.io/docs/configuration.html#resolve-modulesdirectories

这篇关于使用webpack解析需求路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆