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!
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.
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.
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 ...
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",
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With