Javascript 使用 webpack 解析 require 路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27502608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:13:41  来源:igfitidea点击:

Resolving require paths with webpack

javascriptwebpack

提问by gpbl

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

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

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

but I'd like to write

但我想写

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

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

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

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

但是,如果我将别名设置为{ mydir: '/absolute/path/mydir' }require('mydir/myfile.js')则不起作用。

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?

我觉得自己很笨,因为我已经阅读了很多次文档,但我觉得我错过了一些东西。避免使用../../etc编写所有相关要求的正确方法是什么?

采纳答案by AndyCunningham

Webpack >2.0

网络包 >2.0

See wtk's answer.

请参阅wtk 的回答

Webpack 1.0

网络包 1.0

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

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

http://webpack.github.io/docs/configuration.html#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.

解决.root

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

In your case:

在你的情况下:

webpack config

网络包配置

var path = require('path');

// ...

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

consuming module

消费模块

require('myfile')

or

或者

require('myfile.js')

see also: http://webpack.github.io/docs/configuration.html#resolve-modulesdirectories

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

回答by wtk

For future reference, webpack 2 removed everything but modulesas a way to resolve paths. This means rootwill notwork.

为了将来参考,webpack 2 删除了所有内容,但modules作为解析路径的一种方式。这意味着root无法正常工作。

https://gist.github.com/sokra/27b24881210b56bbaff7#resolving-options

https://gist.github.com/sokra/27b24881210b56bbaff7#resolving-options

The example configuration starts with:

示例配置开始于:

{
  modules: [path.resolve(__dirname, "app"), "node_modules"]
  // (was split into `root`, `modulesDirectories` and `fallback` in the old options)

回答by sethro

resolve.aliasshould work exactly the way you described, so I'm providing this as an answer to help mitigate any confusion that may result from the suggestion in the original question that it does not work.

resolve.alias应该完全按照您描述的方式工作,因此我将其作为答案提供,以帮助减轻原始问题中的建议可能导致的任何混淆,即它不起作用。

a resolve configuration like the one below will give you the desired results:

如下所示的解析配置将为您提供所需的结果:

// used to resolve absolute path to project's root directory (where web pack.config.js should be located)
var path = require( 'path' );
...
{
  ...
  resolve: {
    // add alias for application code directory
    alias:{
      mydir: path.resolve( __dirname, 'path', 'to', 'mydir' )
    },
    extensions: [ '', '.js' ]
  }
}

require( 'mydir/myfile.js' )will work as expected. If it does not, there must be some other issue.

require( 'mydir/myfile.js' )将按预期工作。如果没有,那肯定有其他问题。

If you have multiple modules that you want to add to the search path, resolve.rootmakes sense, but if you just want to be able to reference components within your application code without relative paths, aliasseems to be the most straight-forward and explicit.

如果您有多个模块要添加到搜索路径中,这resolve.root是有道理的,但如果您只想能够在没有相对路径的情况下引用应用程序代码中的组件,这alias似乎是最直接和明确的。

An important advantage of aliasis that it gives you the opportunity to namespace your requires which can add clarity to your code; just like it is easy to see from other requires what module is being referenced, aliasallows you to write descriptive requires that make it obvious you're requiring internal modules, e.g. require( 'my-project/component' ). resolve.rootjust plops you into the desired directory without giving you the opportunity to namespace it further.

的一个重要优点alias是它使您有机会为您的requires命名空间,这可以增加您的代码的清晰度;就像很容易从其他requires 中看到正在引用的模块一样,alias允许您编写描述性requires 以明确您需要内部模块,例如require( 'my-project/component' ). resolve.root只是将您放入所需的目录,而不会给您进一步命名它的机会。

回答by Alex Klibisz

In case anyone else runs into this problem, I was able to get it working like this:

万一其他人遇到这个问题,我能够让它像这样工作:

var path = require('path');
// ...
resolve: {
  root: [path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules')],
  extensions: ['', '.js']
};

where my directory structure is:

我的目录结构是:

.
├── dist
├── node_modules
├── package.json
├── README.md
├── src
│?? ├── components
│?? ├── index.html
│?? ├── main.js
│?? └── styles
├── webpack.config.js

Then from anywhere in the srcdirectory I can call:

然后从src目录中的任何地方我可以调用:

import MyComponent from 'components/MyComponent';

回答by SystematicFrank

My biggest headache was working without a namespaced path. Something like this:

我最头疼的是在没有命名空间路径的情况下工作。像这样的东西:

./src/app.js
./src/ui/menu.js
./node_modules/lodash/

Before I used to set my environment to do this:

在我用来设置我的环境来执行此操作之前:

require('app.js')
require('ui/menu')
require('lodash')

I found far more convenient avoiding an implicit srcpath, which hides important context information.

我发现避免src隐藏重要上下文信息的隐式路径要方便得多。

My aim is to require like this:

我的目标是要求这样:

require('src/app.js')
require('src/ui/menu')
require('test/helpers/auth')
require('lodash')

As you see, all my app code lives within a mandatory path namespace. This makes quite clear which require call takes a library, app code or a test file.

如您所见,我所有的应用程序代码都位于一个强制路径命名空间中。这很清楚哪个 require 调用需要库、应用程序代码或测试文件。

For this I make sure that my resolve paths are just node_modulesand the current app folder, unless you namespace your app inside your source folder like src/my_app

为此,我确保我的解析路径只是node_modules当前的应用程序文件夹,除非您在源文件夹中命名您的应用程序,例如src/my_app

This is my default with webpack

这是我使用 webpack 的默认设置

resolve: {
  extensions: ['', '.jsx', '.js', '.json'],
  root: path.resolve(__dirname),
  modulesDirectories: ['node_modules']
}

It would be even better if you set the environment var NODE_PATHto your current project file. This is a more universal solution and it will help if you want to use other tools without webpack: testing, linting...

如果您将环境变量设置为NODE_PATH当前项目文件,那就更好了。这是一个更通用的解决方案,如果你想在没有 webpack 的情况下使用其他工具,它会有所帮助:测试、linting ......

回答by Damjan Pavlica

I have resolve it with Webpack 2 like this:

我已经用 Webpack 2 解决了这个问题:

module.exports = {
  resolve: {
    modules: ["mydir", "node_modules"]    
  }
}

You can add more directories to array...

您可以将更多目录添加到数组...

回答by Aaqib

Got this solved using Webpack 2 :

使用 Webpack 2 解决了这个问题:

   resolve: {
      extensions: ['', '.js'],
        modules: [__dirname , 'node_modules']
    }

回答by Brian Burns

If you're using create-react-app, you can simply add a .envfile containing

如果您使用的是create-react-app,则只需添加一个.env包含以下内容的文件

NODE_PATH=src/

Source: https://medium.com/@ktruong008/absolute-imports-with-create-react-app-4338fbca7e3d

来源:https: //medium.com/@ktruong008/absolute-imports-with-create-react-app-4338fbca7e3d

回答by altShiftDev

This thread is old but since no one posted about require.context I'm going to mention it:

这个帖子很旧,但由于没有人发布有关 require.context 的帖子,我将提及它:

You can use require.context to set the folder to look through like this:

您可以使用 require.context 将文件夹设置为如下所示:

var req = require.context('../../mydir/', true)
// true here is for use subdirectories, you can also specify regex as third param

return req('./myfile.js')

回答by Lucia

Simply use babel-plugin-module-resolver:

只需使用babel-plugin-module-resolver

$ npm i babel-plugin-module-resolver --save-dev

Then create a .babelrcfile under root if you don't have one already:

.babelrc如果您还没有,则在 root 下创建一个文件:

{
    "plugins": [
        [
            "module-resolver",
            {
                "root": ["./"]
            }
        ]
    ]
}

And everything under root will be treated as absolute import:

根下的所有内容都将被视为绝对导入:

import { Layout } from 'components'

For VSCode/Eslint support, see here.

有关 VSCode/Eslint 支持,请参见此处