我有延迟加载和webpack的问题 .
有一个Sean Larkin的视频显示了webpack 4创建一个延迟加载的包(Here)是多么容易 . 但是当我尝试使用打字稿时,我遇到了一些问题 .
index.ts
export const someThing = something => import("./lazy/lazy");
和
lazy/lazy.ts
export default "I am lazy";
当我在没有任何webpack配置的情况下运行它并将文件命名为“.js”时,我得到一个主块和一个用于延迟加载模块的小块 .
但是,当我使用简单的webpack配置将其作为“.ts”文件运行时,我只得到“main.js”文件而没有额外的块 .
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”文件之间究竟有什么区别?
2 回答
Dynamic imports are an ES feature,您需要告诉TypeScript转换为ESNext以在输出上获取
import
,只需将"module": "commonjs"
更改为"module": "esnext"
.拿这个代码:
"module": "commonjs"
编译为module.exports.LoadMe = () => require('a-module')
,Webpack可以't know if it'动态或只是正常require
"module": "esnext"
编译为export const LoadMe = () => import('a-module')
,Webpack知道's dynamic because it'是一个调用表达式import
我有一个技巧,lazyLoad一个模块的类型:
function lazyLoad(){ return let lazyModule:typeof import('xxx') = require('xxx'); }
限制: the xxx can only be string not a variable .