Original translation, please indicate the source when reprinting.
Original address: https://webpack.js.org/guides/code-splitting-import/
Dynamic introduction
Currently, a proposal to add the function-like module loading syntax import() to ECMAScript is under discussion.
The ES2015 loader specification defines import() as a method that can dynamically load ES2015 modules at runtime .
webpack treats import() as a split point, putting required modules into separate code blocks. import() takes the module name as an argument and returns a promise: import(name) -> Promise
index.js
functiondetermineDate(){ import('moment').then(function(moment){ console.log(moment().format()); }).catch(function(err){ console.log('Failed to load moment', err); }); } determineDate();
promise polyfill
If you use import() in older browsers , don't forget to shim promises with a polyfill like es6-promise or promise -polyfill .
(Translator's Note: I didn't find the right words to translate shim and polyfill , its role is to make all versions of browsers compatible with Javascript methods)
In your application's entry point:
import Es6Promise from'es6-promise'; Es6Promise.polyfill(); // or import'es6-promise/auto'; // or import Promise from'promise-polyfill'; if(!window.Promise){ window.Promise = Promise; } // or ...
Use via Babel
If you want to use import via Babel , you need to install or add the syntax-dynamic-import plugin, which is still in stage 3 to avoid compilation errors. This will be completely unnecessary when the proposal is fully incorporated into the fine print.
npm install --save-dev babel-core babel-loader babel-plugin-syntax-dynamic-import babel-preset-es2015 # for this example npm install --save moment
index-es2015.js
functiondetermineDate(){ import ('moment') .then(moment =>moment().format('LLLL')) .then(str => console.log(str)) .catch(err => console.log('Failed to load moment', err)); } determineDate();
webpack.config.js
module.exports ={ entry:'./index-es2015.js', output:{ filename:'dist.js', }, module:{ rules:[{ test:/\.js$/, exclude:/(node_modules)/, use:[{ loader:'babel-loader', options:{ presets:[['es2015',{modules:false}]], plugins:['syntax-dynamic-import'] } }] }] } };
Without the syntax-dynamic-import plugin, the following compilation errors will occur:
- Module build failed: SyntaxError: 'import' and 'export' may only appear at the top
or
- Module build failed: SyntaxError: Unexpected token, expected {
Use via Babel and async/await
ES2017 async/await with import() :
npm install --save-dev babel-plugin-transform-async-to-generator babel-plugin-transform-regenerator babel-plugin-transform-runtime
index-es2017.js
asyncfunctiondetermineDate(){ const moment =awaitimport('moment'); returnmoment().format('LLLL'); } determineDate().then(str => console.log(str));
webpack.config.js
module.exports ={ entry:'./index-es2017.js', output:{ filename:'dist.js', }, module:{ rules:[{ test:/\.js$/, exclude:/(node_modules)/, use:[{ loader:'babel-loader', options:{ presets:[['es2015',{modules:false}]], plugins:[ 'syntax-dynamic-import', 'transform-async-to-generator', 'transform-regenerator', 'transform-runtime' ] } }] }] } };
import instead of require.ensuse ?
Good news: the problem of failing to load code blocks can now be fixed because they are Promise -based .
Warning: require.ensure allows for easy naming of code blocks via optional configuration of the third parameter, but the import API does not yet provide this functionality. If you want to keep this functionality, you can continue to use require.ensure .
require.ensure([],function(require){ var foo =require("./module"); },"custom-chunk-name");
Deprecated System.import
In webpack , using System.import is against the proposed specification, so it was deprecated in v2.1.0-beta.28 in favor of import() .
some examples
- https://github.com/webpack/webpack/tree/master/examples/harmony
- https://github.com/webpack/webpack/tree/master/examples/code-splitting-harmony
- https://github.com/webpack/webpack/tree/master/examples/code-splitting-native-import-context
Web links
-- End --