【问题标题】:Webpack 2 resolve aliasWebpack 2 解析别名
【发布时间】:2017-07-27 02:59:29
【问题描述】:

我在解决 webpack 2 中的别名时遇到了一点问题。无论我做什么,我都无法解决这个问题。以下是相关代码:

/* webpack.mix.js */

       mix.webpackConfig({
         module: {
               rules: [
                   {
                       test: /\.js$/,
                       loader: 'eslint-loader'
                   }
               ]
           },
           resolve: {
             root: path.resolve(__dirname), 
                    // path is reqired at the beggining of file 
             alias: {
               config: 'src/assets/js/config', // this is a config folder
               js: 'src/assets/js'
             }
           }
       });

/* router.js */ 

        import { DashboardRoute } from 'config/route-components'
      // this import is unresolved

【问题讨论】:

    标签: import webpack alias resolve


    【解决方案1】:

    试试这个:

    resolve: {
      root: [
        'node_modules',
        path.resolve('src') // Resolve on root first
      ], 
      alias: {
        config: 'src/assets/js/config', // this is a config folder
        js: 'src/assets/js'
      }
    }
    

    【讨论】:

      【解决方案2】:

      resolve.root 选项在 webpack 2 中不再存在。而是合并到 resolve.modules(来自官方的 Migration Guide)。 Webpack 甚至会抛出它不是有效属性的错误。如果您希望能够从根目录导入,您可以将解析配置更改为:

      resolve: {
        alias: {
          config: 'src/assets/js/config',
          js: 'src/assets/js'
        },
        modules: [
          path.resolve(__dirname),
          'node_modules'
        ]
      }
      

      或者,您可以在 resolve.alias 中使用绝对路径,如下所示:

      resolve: {
        alias: {
          config: path.resolve(__dirname, 'src/assets/js/config'),
          js: path.resolve(__dirname, 'src/assets/js')
        }
      }
      

      【讨论】:

      • 非常感谢您的回答。我遇到了同样的问题,但由于某些奇怪的原因,别名对我不起作用。当我尝试使用别名导入时,我得到:无法解析模块“组件/页面/主”的路径无法解析模块“样式/main.css”的路径还有其他想法吗?
      【解决方案3】:

      在 ionic 3(版本 3.13.3)中,为了使别名映射正常工作,您必须在 webpack.config.jstsconfig.json 中定义路径映射

      请在此处参考完整答案question here

      【讨论】:

        猜你喜欢
        • 2018-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-28
        • 2016-07-21
        • 2019-10-11
        • 1970-01-01
        • 2016-01-16
        相关资源
        最近更新 更多