Vien Nguyen
Vien Nguyen

Reputation: 385

dynamic import in webpack 2 not working

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

Answers (1)

jguffey
jguffey

Reputation: 466

As wuxiandiejia mentioned, the answer is

  1. install babel-plugin-syntax-dynamic-import
  2. make sure 'syntax-dynamic-import' appears in your babel options.plugins

Example babel.rc

{
  "plugins": [
    "syntax-dynamic-import",
}

Upvotes: 9

Related Questions