問(wèn)題:在ts環(huán)境中大猛,babel-plugin-import如何在webpack里面配置按需加載css的功能呢?
官方文檔給出兩種方法關(guān)于如何按需加載笤受。
1..babelrc
里面添加配置(也可以再package.json里面加)
- babel-loader里面添加配置
第二種乳乌,我在社區(qū)找了很多案例也沒(méi)能解決我的問(wèn)題。正因?yàn)榄h(huán)境比較特殊截酷,我這里做了總結(jié):
- 安裝babel-plugin-import插件
- 在babel-loader里面添加該插件
[require.resolve('babel-plugin-import'), {
'libraryName': 'antd',
libraryDirectory: 'lib',
style: true
}]
具體擺放位置:(里面的react-refresh是其他的babel插件)
module: {
rules: [
{
test: /\.tsx?$/,
loaders: [
{
loader: 'babel-loader',
options: {
plugins: [
isDev && require.resolve('react-refresh/babel'),
[require.resolve('babel-plugin-import'), {
'libraryName': 'antd',
libraryDirectory: 'lib',
style: true
}]
].filter(Boolean),
}
},
{
loader: 'ts-loader'
},
]
},
]
}
- 編輯tsconfig.ts
{
"compilerOptions": {
"target": "ES2019", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "es2020", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"strict": true, /* Enable all strict type-checking options. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
}
}
module: "es2020"
要改成es2020,意思就是要ts編譯后的文件的模塊化使用ES module,也就是import
moduleResolution: "node"
是ts按照node尋找包的方式去尋找模塊。
這兩句是能正常運(yùn)行的關(guān)鍵屹培,因?yàn)閎abel-plugin-import實(shí)際上就是尋找import然后在編譯過(guò)程替換成其他代碼
跟它的文檔所寫(xiě)一致。
如:
import { Button } from 'antd';
ReactDOM.render(<Button>xxxx</Button>);
↓ ↓ ↓ ↓ ↓ ↓
var _button = require('antd/lib/button');
require('antd/lib/button/style');
ReactDOM.render(<_button>xxxx</_button>);
所以在發(fā)生按需加載替換代碼之前怔檩,要保證代碼是以ES module的方式加載模塊的褪秀。因此ts才需要配置成ES module