关于后台管理系统所遇到的一些问题

antd中babel-plugin-import插件在create-react-app中失效

按照antd第一篇的介绍设置antd按需加载,需要引入babel-plugin-import插件,然后在.babelrc中设置

// .babelrc or babel-loader option
{
  "plugins": [
    ["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }] // `style: true` 会加载 less 文件
  ]
}

但是,这样设置后还是需要引入样式

import 'antd/dist/antd.css';  // or 'antd/dist/antd.less'

这个让我很尴尬,后面我查了一下stackoverflow,发现在webpack.config.dev.js中的

// Process JS with Babel.
{
  test: /\.(js|jsx|mjs)$/,
  include: paths.appSrc,
  loader: require.resolve('babel-loader'),
  options: {

    // This is a feature of `babel-loader` for webpack (not Babel itself).
    // It enables caching results in ./node_modules/.cache/babel-loader/
    // directory for faster rebuilds.
    cacheDirectory: true,
    plugins: [["import", { libraryName: "antd", style: "css"}]]
  },

这块设置plugins: [[“import”, { libraryName: “antd”, style: “css”}]],这样就解决了在create-react-app中antd按需加载的问题。

create-react-app中使用scss

首先,使用scss需要引用node-sass,sass-loader,css-loader,style-loader

yarn add node-sass
yarn add sass-loader
yarn add css-loader
yarn add style-loader

同时还需要引用file-loader(因为create-react-app中已经引入了file-loader,所以不需要再次添加),在webpack.config.dev.js中module的格式为:

{
  test: /\.scss$/,
  loader: [
    require.resolve('style-loader'),
    require.resolve('css-loader'),
    require.resolve('sass-loader'),
  ]
}

除了这样引用外,还需要在下面的这块添加上/\.scss$/才能生效

// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
  // Exclude `js` files to keep "css" loader working as it injects
  // its runtime that would otherwise processed through "file" loader.
  // Also exclude `html` and `json` extensions so they get processed
  // by webpacks internal loaders.
  exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/, /\.scss$/],
  loader: require.resolve('file-loader'),
  options: {
    name: 'static/media/[name].[hash:8].[ext]',
  },
}