Reputation: 385
I want to use dynamic import in webpack 2. I use webpack 2.4.1
index.js
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import Root from './containers/Root'
import '../styles/custom.scss'
var btn = document.getElementsById('button');
btn.addEventListener("click", () => {
import('./assets/chunk.css').then(()=>{
console.log("Success")
})
});
render(
<Root />,
document.getElementById('root')
)
But when I run "npm start" it didn't work and notify an error at line 9 of index.js
Module build failed: SyntaxError: 'import' and 'export' may only appear at the top level (9:4)
Thanks for any help!
Upvotes: 10
Views: 2390
Reputation: 466
As wuxiandiejia mentioned, the answer is
babel-plugin-syntax-dynamic-import
'syntax-dynamic-import'
appears in your babel options.plugins
Example babel.rc
{
"plugins": [
"syntax-dynamic-import",
}
Upvotes: 9