参考:https://segmentfault.com/a/1190000011128817
这里只是对这篇文章做一个补充。
应我前文的操作,我引入了react-app-rewired 来修改 Webpack 配置。
那么接下来继续引入上面文章提到的 babel-plugin-syntax-dynamic-import 插件。
这里使用 react-app-rewired 的 injectBabelPlugin 函数完成。
最后结果大概是这样。
const tsImportPluginFactory = require('ts-import-plugin')
const { getLoader, injectBabelPlugin } = require("react-app-rewired");
const path = require('path');
function resolve(dir) {
return path.join(__dirname, '.', dir)
}
module.exports = function override(config, env) {
config.resolve.alias = {
...config.resolve.alias,
'@': resolve('src')
}
config = injectBabelPlugin('syntax-dynamic-import', config);
const tsLoader = getLoader(
config.module.rules,
rule =>
rule.loader &&
typeof rule.loader === 'string' &&
rule.loader.includes('ts-loader')
);
tsLoader.options = {
getCustomTransformers: () => ({
before: [tsImportPluginFactory({
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
})]
})
};
return config;
}
然后安装 react-loadable ,修改路由设置。
本来是足够优雅了,但是组件加载的时候我们最好还是给用户一点反馈,于是自然想到了引入 Nprogress 。
本来是想,如果在每一个动态 import 的地方都在前后应用 Nprogress,未免会有太多重复代码,于是写了下面的函数来封装一下
const loadComponent = (path: string) => {
const promise = import(path);
nprogress.start();
promise.then(() => {
nprogress.done();
});
return promise;
}
然后发现,不起作用,提示找不到指定的组件。
直接用import引入可行,这个封装了一层的函数不行。
坑了一会儿之后找到如下描述
Dynamic imports and webpack
Although the specification for
import()supports a dynamic importing of modules in the browser runtime, webpack’srequire.ensure()is not dynamic and requires a hardcoded string to work correctly. For more information see webpack’s documentation on dynamic requires.
好好好。不支持是吧。行。走了。
这个坑放着,以后再看看咋整。
