How to use dynamic import in typescript with webpack application

半城伤御伤魂 提交于 2020-02-12 05:30:10

问题


I have import some of my modules dynamically based on button click, i have used like below"

import { Button } from '@syncfusion/ej2-buttons';

// Initialize Button component.
let button: Button = new Button({ content: 'Button' });

// Render initialized Button.
button.appendTo('#element');

document.getElementById('element').addEventListener("click", function(){
  check();
});

async function check() {
import("@syncfusion/ej2-grids").then((Grid) => {
  debugger
  console.log(Grid);
});
}

my webpack config file:

const path = require("path");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");

module.exports = {
  mode: "development",
  entry: {
    "src/app/bundle": "./src/app/index.ts"
  },
  output: {
    publicPath: "/js/",
    filename: "src/app/bundle.js"
  },
  devtool: "none",
  module: {
    rules: [
      {
        loader: "ts-loader",
        exclude: /node_modules/
      }
    ]
  },

  resolve: {
    extensions: [".ts", ".js"]
  }
};

when i compile and run my application it throws below error

What is the current behavior?

Throws below error

If the current behavior is a bug, please provide the steps to reproduce.

clone sample - https://github.com/kumaresan-subramani/dynamic-import/blob/master/webpack.config.js
run npm i
gulp compile
gulp start

Then click button in browser, you will see reported error in my console.

What is the expected behavior?

Dynamic module should load properly

Other relevant information:

"typescript": "3.7.5",
"uglifyjs-webpack-plugin": "^2.0.1",
"webpack": "^4.29.6",
"webpack-cli": "*",
"webpack-stream": "^5.2.1"
Node.js version: 10.15.1
Operating System: windows 10

回答1:


The whole logic seems weird for me. If you use a module just import it and then use it under certain conditions or after event is triggered



来源:https://stackoverflow.com/questions/60056219/how-to-use-dynamic-import-in-typescript-with-webpack-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!