我正在尝试使用ES6中的动态模块加载功能,它似乎尚未实际实现.但是像
ES6 Module Loader Polyfill这样的替代品应该暂时可以做到.
所以我使用Babel和Webpack将ES6项目转换为ES5,并且它可以自行运行.但是我的所有代码都合并到一个bundle.js文件中,我希望将其拆分为模块.当我尝试提到的Polyfill时,它会从内部抛出一些错误,项目甚至不会启动.
index.js:6 Uncaught TypeError: Cannot read property 'match' of undefined
第6行读到:
var filePrefix = 'file:' + (process.platform.match(/^win/) ? '/' : '') + '//';
这是我的package.js文件:
{ "dependencies": { "es6-module-loader": "^0.17.11","events": "^1.1.0","flux": "^2.1.1","fs": "0.0.2","react": "^15.0.2","react-addons-css-transition-group": "^15.0.2","react-dom": "^15.0.2","react-router": "^2.4.0","react-tap-event-plugin": "^1.0.0",},"devDependencies": { "babel-core": "^6.8.0","babel-loader": "^6.2.4","babel-preset-es2015": "^6.6.0","babel-preset-react": "^6.5.0","html-webpack-plugin": "^2.16.1","react-hot-loader": "^1.3.0","transfer-webpack-plugin": "^0.1.4","webpack": "^1.13.0",} }
有人可以指点一下使用Webpack和Babel加载动态模块的工作示例吗?
解决方法
这里真的有三件事……
dynamic
importing,延迟加载和代码拆分/捆绑.使用
ES6 Module Loader进行多边形填充的System.import方法将允许动态导入,但不允许动态导入
code splitting:
However,most transpilers do not support converting
System.load
calls torequire.ensure
so you have to do that directly if you want to make use of dynamic code splitting.
动态代码拆分是指在入口点内创建子包时,然后可以动态延迟加载.为此,我建议使用比require.ensure更友好的promise-loader:
import LoadEditor from 'promise?global,[name]!./editor.js'; ... if (page === 'editor') { LoadEditor().then(Editor => { // Use the Editor bundle... }) }
Webpack现在将edit.js模块及其所有依赖项分解为一个单独的bundle,可以立即或动态加载(如上所示).最后,根据应用程序的大小,我认为你也应该考虑splitting the vendor code out.
UPDATE
System.import已从规范中删除,只需import()替换.新的webpack文档在webpack中有一个page that discusses dynamic imports以及它们的局限性.