简体   繁体   English

Webpack:配置路径映射

[英]Webpack: configure path mapping

This is probably a trivial problem, but I am new to webpack.这可能是一个微不足道的问题,但我是 webpack 的新手。 I have a project where the include paths seem to be messed up.我有一个项目,其中包含路径似乎搞砸了。 The project structure looks like this (simplified):项目结构如下(简化):

app/
├─ webpack.config.js
├─ dist/
├─ src/
│  ├─ main.js
│  ├─ modules/
│  │  ├─ button/
│  │  │  ├─ button.js
│  │  ├─ link/
│  │  │  ├─ link.js
      ... many more

Note that each module has its own subfolder.请注意,每个模块都有自己的子文件夹。 The main.js looks like this: main.js看起来像这样:

import './modules/button';
import './modules/link';
...

Modules can import other modules:模块可以导入其他模块:

// app/src/modules/button/button.js
import { mediaLink } from '../link';

I have a basic webpack.config.js set up that looks like this:我有一个基本的webpack.config.js设置,如下所示:

const path = require('path');

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.js',
  },
};

For some reason, all imports don't consider the module's subfolders.出于某种原因,所有导入都不考虑模块的子文件夹。 When i run webpack , I get a lot of Module not found: Error: Can't resolve... errors.当我运行webpack时,我得到很多Module not found: Error: Can't resolve...错误。 The error output looks like this:错误 output 如下所示:

ERROR in ./src/main.js
Module not found: Error: Can't resolve './modules/button' in '/path/to/project/app/src'
 @ ./src/main.js 8:0-27

Can I configure webpack to use some kind of mapping when it imports a module?我可以将 webpack 配置为在导入模块时使用某种映射吗?

If the tree is如果树是

├─ src/
│  ├─ main.js
│  ├─ modules/
│  │  ├─ button/
│  │  │  ├─ button.js

then src/main.js will need to然后src/main.js将需要

import './modules/button/button';

or, if button.js was named index.js ( resolve.mainFiles ) ,或者,如果button.js 被命名为index.js ( resolve.mainFiles )

import './modules/button';

would work.会工作。

Yes, you can set up aliases/mappings, but that's probably not worth it (especially when you consider your IDE/editor/... would also need to know about the mappings).是的,您可以设置别名/映射,但这可能不值得(特别是当您考虑您的 IDE/编辑器/... 也需要了解映射时)。

Just try renaming those button/button.js es and link/link.js es to button/index.js , link/index.js etc. first.只需先尝试将那些button/button.js es 和link/link.js es 重命名为button/index.jslink/index.js等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM