如何为文件夹设置webpack 2别名?

时间:2017-08-30 19:46:17

标签: reactjs webpack webpack-2

我有一个反应项目,如下所示:

train_df.Fedu.value_counts().sort_index().plot(kind='bar')

我的问题是:

有没有办法设置允许我调用themes文件夹中任何文件的别名?

我正在使用webpack 2,我找到了类似这样的东西:

app
 |_ components
 |_ containers
 |_ actions
 |_ reducers
 |_ themes
      |_ theme1
           |_ index.jsx
      |_ theme2
           |_ index.jsx

package.json
webpack.config.js

我还想以下列方式导入这些文件:

resolve: { extensions: ['*', '.js', '.jsx'], alias: { Themes$: path.resolve(__dirname, 'src/themes/') } },

当我运行我的项目时,我收到以下错误:

  

4:1错误'主题'应该列在项目的依赖项中。   运行' npm i -S主题'添加它import / no-extraneous-dependencies
  4:8错误'模板'已定义但从未使用过   no-unused-vars 4:23错误在''主题''之前找到多个空格   no-multi-spaces 4:23错误绝对导入应该在之前   相对进口进口/第一
  4:23错误无法解析模块的路径'主题'
  import / no-unresolved 4:23错误缺少文件扩展名   "主题"

我在this documentation中找到了一些示例,但我无法找到实现它的正确方法。谁能告诉我如何以正确的方式设置我的webpack配置?

以下是 webpack.config.js

import * as Themes from 'Themes';

1 个答案:

答案 0 :(得分:0)

尝试将配置更改为变体,其别名如下所示:

resolve: {
    extensions: ['*', '.js', '.jsx'],
    alias: {
      Themes: path.resolve(__dirname, 'src/themes/')
    }
  },

然后添加到themes目录index.js(路径:app / themes / index.js):

import * as theme1 from './theme1';
import * as theme2 from './theme2';

export default {
  theme1,
  theme2
}

文件:app / themes / theme1 / index.jsx应该导出theme1目录中所有员工的对象。

import Someting from './Someting';
import Anything from './Anything';

export default {
   Someting,
   Anything
}

现在你可以尝试:

import * as MyThemes from 'Themes';
console.log(MyThemes.theme1.Someting);
console.log(MyThemes.theme1.Anything);

import MyFirstTheme from 'Themes/theme1';
console.log(MyFirstTheme.Someting);
console.log(MyFirstTheme.Anything);

theme2目录的所有内容都是一样的。