babel-plugin-import icon indicating copy to clipboard operation
babel-plugin-import copied to clipboard

working with material ui

Open zwhitchcox opened this issue 7 years ago • 4 comments

I set my babel plugins to be this:

      [
         "babel-plugin-import",
         {
            "libraryName": "@material-ui/core",
            "libraryDirectory": "",
            "camel2DashComponentName": false
         },
         "tree-shaking-mui-core"
      ],
      [
         "babel-plugin-import",
         {
            "libraryName": "@material-ui/core/styles",
            "libraryDirectory": "",
            "camel2DashComponentName": false
         },
         "tree-shaking-mui-styles"
      ],
      [
         "babel-plugin-import",
         {
            "libraryName": "@material-ui/core/colors",
            "libraryDirectory": "",
            "camel2DashComponentName": false
         },
         "tree-shaking-mui-colors"
      ],
      [
         "babel-plugin-import",
         {
            "libraryName": "@material-ui/icons",
            "libraryDirectory": "",
            "camel2DashComponentName": false
         },
         "tree-shaking-mui-icons"
      ]

but I still get the error

ERROR in ./src/main/snack/cmpt.js
Module not found: Error: Can't resolve '@material-ui/core/withStyles' in '/home/zane/dev/ashworthfirm/src/main/snack'
 @ ./src/main/snack/cmpt.js 24:42-81
 @ ./src/main/main.js
 @ ./src/main/client.js
 @ multi ./src/main/client.js

It seems to disregard the second directory specification, as withStyles is stored in @material-ui/core/styles. It seems like other people have gotten this to work, but I can't figure out why it's not working for me....here's the full webpack file:

const cp = require('child_process')
const fs = require('fs')
const path = require('path')

const project_root = process.cwd()
const server_path = check_args(['-s', '--server']) || `${project_root}/src/server.js`
const client_path = check_args(['-c', '--client']) || `${project_root}/src/client.js`
const build_path = check_args(['-b', '--build']) || `${project_root}/build`

const require_root = mod => require(path.resolve(project_root, 'node_modules', mod))
const rimraf = require_root('rimraf')
const ncp = require_root('ncp').ncp
const webpack = require_root('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const MiniCssExtractPlugin = require_root('mini-css-extract-plugin')
const WebpackSourceMapSupport = require_root('webpack-source-map-support')
const InstallDeps = require_root('webpack-plugin-install-deps')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const Clean = require_root('clean-webpack-plugin')
const nodeExternals = require_root('webpack-node-externals');
const babel_preset_env = require_root('@babel/preset-env')
const babel_preset_react = require_root('@babel/preset-react')
const babel_plugin_transform_runtime = require_root('@babel/plugin-transform-runtime')
const babel_plugin_proposal_class_properties = require_root('@babel/plugin-proposal-class-properties')
const babel_plugin_import = require('babel-plugin-import')

const babelrc_path = project_root + '/.babelrc'
rimraf.sync(build_path)
const client_exists = fs.existsSync(client_path)
const server_exists = fs.existsSync(server_path)
const babelrc_exists = fs.existsSync(babelrc_path)

const output_opts = {
  colors: { level: 3, hasBasic: true, has256: true, has16m: true },
  cached: false,
  cachedAssets: false,
  entrypoints: false,
  exclude: [ 'node_modules', 'bower_components', 'components' ],
  infoVerbosity: 'info',
}

let babel_opts = {
  presets: [
    babel_preset_env,
    babel_preset_react,
  ],
  plugins: [
    babel_plugin_transform_runtime,
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-proposal-class-properties', { loose: true }],
    [
       "babel-plugin-import",
       {
          "libraryName": "@material-ui/core",
          "libraryDirectory": "",
          "camel2DashComponentName": false
       },
       "tree-shaking-mui-core"
    ],
    [
       "babel-plugin-import",
       {
          "libraryName": "@material-ui/core/styles",
          "libraryDirectory": "",
          "camel2DashComponentName": false
       },
       "tree-shaking-mui-styles"
    ],
    [
       "babel-plugin-import",
       {
          "libraryName": "@material-ui/core/colors",
          "libraryDirectory": "",
          "camel2DashComponentName": false
       },
       "tree-shaking-mui-colors"
    ],
    [
       "babel-plugin-import",
       {
          "libraryName": "@material-ui/icons",
          "libraryDirectory": "",
          "camel2DashComponentName": false
       },
       "tree-shaking-mui-icons"
    ]
  ],
}
if (babelrc_exists) {
  const babelrc = fs.readFileSync(babelrc_path)
  babel_opts = JSON.parse(babelrc)
}

const client_config = {
  entry: [
    client_path,
  ],
  module: {
    rules: [
      {
        test: /\.svg$/,
        use: [
          {
            loader: "babel-loader"
          },
          {
            loader: "react-svg-loader",
            options: {
              jsx: true,
            }
          }
        ]
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: babel_opts,
        },
      },
      {
        test: /\.(css)$/,
        exclude: /node_modules/,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader"
        ]
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192
            }
          }
        ]
      }
    ]
  },
  output: {
    path: build_path,
    publicPath: '/',
    filename: 'client.js'
  },
  plugins: [
    new BundleAnalyzerPlugin(),
    new webpack.IgnorePlugin(/\/iconv-loader$/),
    new MiniCssExtractPlugin({
      filename: "main.css",
      chunkFilesname: "[id].css",
    }),
    new webpack.DefinePlugin({
      'process.env.BROWSER': true,
      'process.env.SERVER': false,
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
    new UglifyJsPlugin(),
  ],
  stats: 'minimal',
  target: 'web',
  context: project_root,
  mode: 'development',
}

const server_config = {
  entry: [
    server_path,
  ],
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: babel_opts,
        },
      },
      {
        test: /\.(css)$/,
        exclude: /node_modules/,
        use: ['css-loader']
      }
    ]
  },
  output: {
    path: build_path,
    publicPath: '/',
    filename: 'server.js'
  },
  plugins: [
    new webpack.IgnorePlugin(/\/iconv-loader$/),
    new webpack.DefinePlugin({
      'process.env.BROWSER': false,
      'process.env.SERVER': true,
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
  ],
  target: 'node',
  externals: [nodeExternals()],
  devtool: 'eval-source-map',
  mode: 'development',
  context: project_root,
  node: {
    __dirname: false,
  },
  stats: 'minimal',
}

if (!(server_exists || client_exists)) {
  throw new Error('neither client, nor server files were found')
} else {
  console.log('building...')
}


let server_process;
if (server_exists) {
  webpack(server_config).run((err, stats) => {
    console.log(stats.toString(output_opts))
  })
}
if (client_exists) {
  webpack(client_config).run((err, stats) => {
    console.log(stats.toString(output_opts))
  })
}

function check_args(check_arg) {
  check_arg = [].concat(check_arg)
  const args = process.argv.slice(2)
  let idx;
  let passed;
  if (~(idx = args.findIndex(arg => check_arg.includes(arg)))) {
    return args[idx + 1]
  }
  if (!passed) return
  if (passed[0] === path.delimiter) {
    return passed
  }
}

zwhitchcox avatar Jul 27 '18 15:07 zwhitchcox

@zwhitchcox Did you manage to solve this?

williamluke4 avatar Jan 26 '19 09:01 williamluke4

I think I did, but I don't remember what I did

zwhitchcox avatar Jan 26 '19 15:01 zwhitchcox

@zwhitchcox Sorted it Changed this

import { createStyles, WithStyles, withStyles, Theme } from '@material-ui/core';

To this

import { createStyles, WithStyles, withStyles, Theme } from '@material-ui/core/styles';

williamluke4 avatar Jan 26 '19 15:01 williamluke4

@zwhitchcox Sorted it Changed this

import { createStyles, WithStyles, withStyles, Theme } from '@material-ui/core';

To this

import { createStyles, WithStyles, withStyles, Theme } from '@material-ui/core/styles';

这个修改可以使用,但是如果是优化已有项目,这个改动量惊人,有没有什么更好办法

This is because @material-ui/styles is re-exported through core, but the full import is not allowed. https://material-ui.com/zh/guides/minimizing-bundle-size/

foxundermoon avatar Nov 28 '19 16:11 foxundermoon