2017-04-17 15:33:40 +00:00
|
|
|
// Based on https://github.com/airbnb/babel-plugin-dynamic-import-webpack
|
|
|
|
// We've added support for SSR with this version
|
|
|
|
import template from 'babel-template'
|
|
|
|
import syntax from 'babel-plugin-syntax-dynamic-import'
|
|
|
|
import UUID from 'uuid'
|
|
|
|
|
|
|
|
const TYPE_IMPORT = 'Import'
|
|
|
|
|
|
|
|
const buildImport = (args) => (template(`
|
|
|
|
(
|
2017-04-19 18:25:06 +00:00
|
|
|
typeof window === 'undefined' ?
|
|
|
|
new (require('next/dynamic').SameLoopPromise)((resolve, reject) => {
|
|
|
|
eval('require.ensure = function (deps, callback) { callback(require) }')
|
|
|
|
require.ensure([], (require) => {
|
|
|
|
let m = require(SOURCE)
|
|
|
|
m = m.default || m
|
|
|
|
m.__webpackChunkName = '${args.name}.js'
|
|
|
|
resolve(m);
|
|
|
|
}, 'chunks/${args.name}.js');
|
|
|
|
})
|
|
|
|
:
|
|
|
|
new (require('next/dynamic').SameLoopPromise)((resolve, reject) => {
|
|
|
|
const weakId = require.resolveWeak(SOURCE)
|
|
|
|
try {
|
|
|
|
const weakModule = __webpack_require__(weakId)
|
|
|
|
return resolve(weakModule.default || weakModule)
|
|
|
|
} catch (err) {}
|
2017-04-17 15:33:40 +00:00
|
|
|
|
2017-04-19 18:25:06 +00:00
|
|
|
require.ensure([], (require) => {
|
|
|
|
try {
|
2017-04-17 20:15:50 +00:00
|
|
|
let m = require(SOURCE)
|
|
|
|
m = m.default || m
|
2017-04-19 18:25:06 +00:00
|
|
|
resolve(m)
|
|
|
|
} catch(error) {
|
|
|
|
reject(error)
|
|
|
|
}
|
|
|
|
}, 'chunks/${args.name}.js');
|
|
|
|
})
|
2017-04-17 15:33:40 +00:00
|
|
|
)
|
|
|
|
`))
|
|
|
|
|
|
|
|
export default () => ({
|
|
|
|
inherits: syntax,
|
|
|
|
|
|
|
|
visitor: {
|
|
|
|
CallExpression (path) {
|
|
|
|
if (path.node.callee.type === TYPE_IMPORT) {
|
2017-06-29 00:25:13 +00:00
|
|
|
const moduleName = path.node.arguments[0].value
|
|
|
|
const name = `${moduleName.replace(/[^\w]/g, '-')}-${UUID.v4()}`
|
2017-04-17 15:33:40 +00:00
|
|
|
const newImport = buildImport({
|
2017-06-29 00:25:13 +00:00
|
|
|
name
|
2017-04-17 15:33:40 +00:00
|
|
|
})({
|
|
|
|
SOURCE: path.node.arguments
|
|
|
|
})
|
|
|
|
path.replaceWith(newImport)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|