为什么Dynamic需要(表达式)webpack无法正常工作

时间:2016-05-27 07:00:03

标签: angularjs node.js webpack require

我试图使用下面的代码懒惰加载我的路线状态

//router.js
//usage
$stateProvider
  .state('async', {
    url: '/async',
    templateUrl: require('!!file-loader?name=templates/[name].[ext]!./../../pages/somepage/page.html'),
    controller: 'asyncController',
    resolve: {
      deps: 
      asyncPreloading: resolverProvider.lazyload('../../pages/somepage/page.module.js')
    }
  })

" resolverProvider.lazyload(path)"当尝试要求(路径)时,我得到警告,如

  

关键依赖项:   30:34-55依赖的请求是表达式

  

关键依赖项:   30:34-41要求函数以不能静态提取依赖关系的方式使用

resolverProvider代码位于

之下
//provider.js
'use strict';
export default function (app) {
  app.provider('resolver', resolverProvider);

  function resolverProvider() {
      this.$get = () => this;
      this.lazyload = lazyload;
  }

  function lazyload(module) {
    return (($q, $ocLazyLoad) => {
      "ngInject";

      const deferred = $q.defer();

      require.ensure([], function (require) {
          console.log(module);
          const asyncModule = require('../../pages/somepage/page.module.js'); // it works
          const asyncModule = require(module); // doesn't work
          $ocLazyLoad.load({
              name: asyncModule.name,
          });
          deferred.resolve(asyncModule.controller);
      });
      return deferred.promise;
    });
  }
}

有没有人能解决动态 require(表达);

这个问题

2 个答案:

答案 0 :(得分:0)

解决方案是require.contextwebpack

我创建了webpackConfig.resolve.alias指向我的appRoot

当我执行require(path)时,我将我的路径视为regex

//provider.js

const asyncModule = require('_appRoot/' + moduleRegExp + '.js');

结帐webpack了解更多信息。

我的webpack配置如下:

// resolves modules
resolve: {
  extensions: ['', '.js'],
  modulesDirectories: ['node_modules'],
  alias: {
    _appRoot:     path.join(_path, 'src', 'app'),
    _images:      path.join(_path, 'src', 'app', 'assets', 'images'),
    _stylesheets: path.join(_path, 'src', 'app', 'assets', 'styles'),
    _scripts:     path.join(_path, 'src', 'app', 'assets', 'js')
  }
},

我的路线状态如下 asyncPreloading: resolverProvider.lazyload('pages\/async-page-example\/async.module')

答案 1 :(得分:0)

在不借助eval的情况下实现这一目标的更简单方法是:

const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
const foo = requireFunc(moduleName);

在捆绑的输出中,它将变为

const requireFunc = true ? require : require;
const foo = requireFunc(moduleName);

有关更多选项,请点击此处:https://github.com/webpack/webpack/issues/4175