使用 Typescript 进行 Webpack 延迟加载 [英] Webpack Lazy Loading with Typescript
问题描述
我有延迟加载和 webpack 的问题.
I have a problem with lazy loading and webpack.
有一段 Sean Larkin 的视频,展示了使用 webpack 4 创建延迟加载包是多么容易(此处).但是当我尝试用打字稿来做这件事时,我遇到了一些问题.
There is a video of Sean Larkin showing how easy it is with webpack 4 to create a lazy loaded bundle (Here). But when I try to do it with typescript I run into some problems.
index.ts
export const someThing = something => import("./lazy/lazy");
和
lazy/lazy.ts
export default "I am lazy";
当我在没有任何 webpack 配置的情况下运行它并将文件命名为.js"时,我得到一个主块和一个用于延迟加载模块的小块.
when I run it without any webpack configuration and name the files to ".js" I get a main chunk and a small chunk for the lazy loaded module.
但是当我使用简单的 webpack 配置将它作为.ts"文件运行时,我只得到main.js"文件而没有额外的块.
But when I run it as ".ts" files with a simple webpack configuration I get just the "main.js" file and no extra chunk.
webpack.config.js
let config = {
resolve: {
extensions: [".ts", ".js"]
},
module: {
rules: [
{ test: /\.ts$/, use: ["ts-loader"], exclude: /node_modules/ },
]
},
}
module.exports = config;
和
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": true,
"lib": [ "es6", "dom" ],
"removeComments": true
}
}
有什么要配置的吗?我是任务吗?将js"文件导入ts"文件到底有什么区别?
Is there something to configure I am mission? What exactly is the difference between the import of a "js" file to a "ts" file?
推荐答案
动态导入是 ES 功能,你需要告诉 TypeScript 转换为 ESNext 得到 import
在输出上,只需将 "module": "commonjs"
更改为 "module": "esnext"
.
Dynamic imports are an ES feature, you need to tell TypeScript to transform to ESNext to get import
on the output, just change "module": "commonjs"
to "module": "esnext"
.
拿这个代码:
export const LoadMe = () => import('./a-module')
"module": "commonjs"
编译为module.exports.LoadMe = () =>require('a-module')
,Webpack 无法知道它是动态的还是只是一个普通的require
"module": "esnext"
编译为export const LoadMe = () =>import('a-module')
,Webpack 知道它是动态的,因为它是对import
的调用表达式
"module": "commonjs"
compiles tomodule.exports.LoadMe = () => require('a-module')
, Webpack can't know if it's dynamic or just a normalrequire
"module": "esnext"
compiles toexport const LoadMe = () => import('a-module')
, Webpack knows it's dynamic because it's a call expression toimport
这篇关于使用 Typescript 进行 Webpack 延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!