Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic import in webpack 2 not working

Tags:

webpack-2

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!

like image 919
Vien Nguyen Avatar asked Apr 28 '17 07:04

Vien Nguyen


People also ask

How does Webpack dynamic import work?

Whenever you import a file in your code, Webpack will look for it in the project directory and copy it to the build folder with a new name, then Webpack replaces the import code in your bundled JavaScript file with the path to the newly copied file.

How do dynamic imports work?

Dynamic import of modulesIt returns a promise and starts an asynchronous task to load the module. If the module was loaded successfully, then the promise resolves to the module content, otherwise, the promise rejects.

How do I use dynamic import in react?

import { lazy, Suspense } from "react"; import { Routes, Route, Outlet, Link } from "react-router-dom"; import HomePage from "./pages/Home"; const Dashboard = lazy(() => import("./pages/Dashboard")); const Notifications = lazy(() => import("./pages/Notifications")); export default function App() { return ( <div ...


1 Answers

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",
}
like image 148
jguffey Avatar answered Sep 28 '22 10:09

jguffey