关于babel-plugin-import的问题

问题:在ts环境中,babel-plugin-import如何在webpack里面配置按需加载css的功能呢?
官方文档给出两种方法关于如何按需加载。
1..babelrc里面添加配置(也可以再package.json里面加)

  1. babel-loader里面添加配置

第二种,我在社区找了很多案例也没能解决我的问题。正因为环境比较特殊,我这里做了总结:

  • 安装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寻找包的方式去寻找模块。
这两句是能正常运行的关键,因为babel-plugin-import实际上就是寻找import然后在编译过程替换成其他代码
跟它的文档所写一致。
如:

import { Button } from 'antd';
ReactDOM.render();

      ↓ ↓ ↓ ↓ ↓ ↓

var _button = require('antd/lib/button');
require('antd/lib/button/style');
ReactDOM.render(<_button>xxxx);

所以在发生按需加载替换代码之前,要保证代码是以ES module的方式加载模块的。因此ts才需要配置成ES module

你可能感兴趣的:(关于babel-plugin-import的问题)