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

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

问题描述

我仍然对如何使用 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

包含您的模块的目录(绝对路径).也可能是一个目录数组.此设置应用于将单个目录添加到搜索路径.

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']
  }

消费模块

require('myfile')

require('myfile.js')

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

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

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