Code Monkey home page Code Monkey logo

babel-plugin-component's People

Contributors

afc163 avatar hzsrc avatar leopoldthecoder avatar qingwei-li avatar sorrycc avatar yiminghe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

babel-plugin-component's Issues

Fails to install with vue-cli 3.0

Version

Latest

Reproduction link

https://github.com/cristijora/vue-cli-element-ui

Steps to reproduce

  1. Init repo
  2. Try to run yarn serve

What is expected?

Babel plugin component installation doesn't fail

What is actually happening?

https://www.npmjs.com/package/babel-plugin-component The plugin is not applied and the webpack server fails.

Module build failed: Error: .plugins[0][1] must be an object, false, or undefined
at assertPluginItem (/Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/config/validation/option-assertions.js:155:15)
at /Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/config/validation/option-assertions.js:132:14
at Array.forEach ()
at assertPluginList (/Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/config/validation/option-assertions.js:131:9)
at /Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/config/validation/options.js:83:20
at Array.forEach ()
at validate (/Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/config/validation/options.js:61:21)
at /Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/config/config-chain.js:136:36
at cachedFunction (/Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/config/caching.js:40:17)
at init (/Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/config/config-chain.js:117:12)
at /Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/config/config-chain.js:201:17
at buildRootChain (/Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/config/config-chain.js:82:20)
at loadConfig (/Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/config/index.js:50:53)
at transformSync (/Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/transform-sync.js:13:36)
at Object.transform (/Users/cristij/CreativeTim/new-proj/node_modules/@babel/core/lib/transform.js:20:65)
at transpile (/Users/cristij/CreativeTim/new-proj/node_modules/babel-loader/lib/index.js:55:20)
at Object.module.exports (/Users/cristij/CreativeTim/new-proj/node_modules/babel-loader/lib/index.js:179:20)

@ multi (webpack)-dev-server/client?http://localhost:8082/ (webpack)/hot/dev-server.js ./src/main.js


Vue-cli issue vuejs/vue-cli#739

typeof一个模块都是undefined,new构造函数提示not defined

模块lib/socket-connection.js

module.exports = function SocketConnection () {}

引入:

import { SocketConnection } from 'xxx'

console.log(typeof SocketConnection) // undefined
console.log(SocketConnection) // function SocketConnection () {}

SocketConnection() // 正常执行函数
new SocketConnection() // Uncaught ReferenceError: SocketConnection is not defined

webpack 2.2.1 搭配插件按需引入组件自定义主题 打包问题

babel配置如下

{
  "plugins": [
    "transform-es2015-template-literals",
    "syntax-dynamic-import",
    "lodash",
    ["component", [
      {
        "libraryName": "element-ui"
      }
    ]]
  ],
  "env": {
    "dev": {
      "presets":[
        ["env", {
          "targets": {
            "chrome": 58
          },
          "modules": false,
          "loose": true
        }]
      ]
    },
    "prod":{
      "presets": [["es2015",{ "modules": false }]]
    }
  }
}

在开发模式 全部 style-loader非extract下 自定义主题没有问题,
生产模式 使用extract-text-webpack-plugin后,
vue的异步组件出现报错或未实例化,最后勉强手动import css,

包版本

{
"extract-text-webpack-plugin": "2.1.0",
"webpack": "2.2.1",
"vue-template-compiler": "2.2.1",
"vue-loader": "^11.1.4",
 "vue": "2.2.1"
}

error when use babel-preset-env

babel

{
	"presets": [
		["env", {
			"useBuiltIns": "usage",
			"modules": false,
			"targets": {
				"browsers": ["last 5 versions", "ie >= 9"]
			}
		}]
	],
	"comments": false,
	"env": {
		"test": {
			"presets": ["env", "stage-2"],
			"plugins": ["istanbul"]
		}
	},
	"plugins": [
		"lodash",
		["transform-object-rest-spread", { "useBuiltIns": true }],
		["component", [
			{
			  "libraryName": "element-ui",
			  "styleLibraryName": "theme-default"
			}
		  ]]
	]
}

error in ./src/utils/logic-error.js

Module build failed: TypeError: E:\git\byd\web\src\utils\logic-error.js: Cannot read property 'file' of undefined
at buildExpressionHandler (E:\git\byd\web\node_modules\babel-plugin-component\lib\core.js:125:26)
at PluginPass.IfStatement (E:\git\byd\web\node_modules\babel-plugin-component\lib\core.js:266:11)
at newFn (E:\git\byd\web\node_modules\babel-traverse\lib\visitors.js:236:21)
at NodePath._call (E:\git\byd\web\node_modules\babel-traverse\lib\path\context.js:68:19)
at NodePath.call (E:\git\byd\web\node_modules\babel-traverse\lib\path\context.js:42:17)
at NodePath.visit (E:\git\byd\web\node_modules\babel-traverse\lib\path\context.js:99:12)
at TraversalContext.visitQueue (E:\git\byd\web\node_modules\babel-traverse\lib\context.js:137:18)
at TraversalContext.visitMultiple (E:\git\byd\web\node_modules\babel-traverse\lib\context.js:91:17)
at TraversalContext.visit (E:\git\byd\web\node_modules\babel-traverse\lib\context.js:176:19)
at Function.traverse.node (E:\git\byd\web\node_modules\babel-traverse\lib\index.js:108:17)
at NodePath.visit (E:\git\byd\web\node_modules\babel-traverse\lib\path\context.js:110:19)
at TraversalContext.visitQueue (E:\git\byd\web\node_modules\babel-traverse\lib\context.js:137:18)
at TraversalContext.visitSingle (E:\git\byd\web\node_modules\babel-traverse\lib\context.js:96:19)
at TraversalContext.visit (E:\git\byd\web\node_modules\babel-traverse\lib\context.js:178:19)
at Function.traverse.node (E:\git\byd\web\node_modules\babel-traverse\lib\index.js:108:17)
at NodePath.visit (E:\git\byd\web\node_modules\babel-traverse\lib\path\context.js:110:19)

@ ./src/utils/api-client.js 3:0-39
@ ./src/store/index.js
@ ./src/main.js
@ multi ./build/dev-client ./src/main.js

使用 import { Button as Ebutton } from 'element-ui' 报错

使用 import { Button as Ebutton } from 'element-ui' 报错
报错内容如图
image
babelrc 配置

{
    "presets": [],
    "plugins": [
        "transform-vue-jsx",
        ["component",[{
            "libraryName": "element-ui",
            "styleLibraryName": "theme-default"
          }]]]
}

webpack 版本 2.4.1

js路径和css路径必须都是基于libDir的变量控制,能否分开

能否使js路径基于/lib,而css/scss路径基于非lib的路径,比如packages,thx!
用于支持自定义主题的按需引入(引入变量方式)
Converts

import { Button } from 'element-ui'

To

var button = require('element-ui/lib/button')
require('element-ui/packages/theme-chalk/src/button.scss')

await in try without catch throws type error

Input Code

// actions.js
import * as types from './mutation_types';
import * as apiClient from 'lib/api_client';

export async function getLoginState({ commit }) {
    try {
        commit(types.FULLSCREEN_LOADING_START);
        const { error, success, response, message } = await apiClient.getLoginState();
        if (error === false && success === true) {
            commit(types.RECEIVED_LOGIN_STATE, { loggedIn: response.loggedIn });
            commit(types.RECEIVED_CSRF_TOKEN, { csrfToken: response.csrfToken });
        } else {
            commit(types.UPDATE_GLOBAL_ALERT, {
                title: message,
                type: 'error'
            });
        }
    } finally {
        commit(types.FULLSCREEN_LOADING_STOP);
    }
}

Babel Configuration (.babelrc)

{
    "presets": [
        ["es2015", {
            "modules": false
        }],
        "stage-1"
    ],
    "plugins": [
        "lodash",
        "syntax-dynamic-import", ["component", [{
            "libraryName": "element-ui",
            "styleLibraryName": "theme-default"
        }]],
        "transform-runtime"
    ],
    "comments": false,
    "env": {
        "test": {
            "plugins": ["istanbul"]
        }
    }
}

Current Behavior

The configuration should have been able to parse async await functions but I was getting the following error:

Error stack trace
ERROR in ./src/client/store/actions.js
Module build failed: TypeError: /home/suhas/workspace/vista/src/client/store/actions.js: Cannot read property 'name' of null
    at /home/suhas/workspace/vista/node_modules/babel-plugin-component/lib/core.js:204:33
    at Array.forEach (native)
    at PluginPass.ArrayExpression (/home/suhas/workspace/vista/node_modules/babel-plugin-component/lib/core.js:203:20)
    at newFn (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/visitors.js:276:21)
    at NodePath._call (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/path/context.js:48:17)
    at NodePath.visit (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/path/context.js:105:12)
    at TraversalContext.visitQueue (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitMultiple (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/context.js:103:17)
    at TraversalContext.visit (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/context.js:190:19)
    at Function.traverse.node (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/index.js:114:17)
    at NodePath.visit (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/path/context.js:115:19)
    at TraversalContext.visitQueue (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitMultiple (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/context.js:103:17)
    at TraversalContext.visit (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/context.js:190:19)
    at Function.traverse.node (/home/suhas/workspace/vista/node_modules/babel-traverse/lib/index.js:114:17)
 @ ./src/client/store/index.js 4:0-37 28:4-34:6 28:65-34:5 31:21-41
 @ ./src/client/main.js
 @ multi ./build/dev-client ./src/client/main.js

I could not replicate the error in the babel online repl.

Possible Solution

It is possible to work around this problem by including a catch block:

import * as types from './mutation_types';
import * as apiClient from 'lib/api_client';

/* eslint-disable require-jsdoc */
export async function getLoginState({ commit }) {
    try {
        // ...
    } catch (err) {
        commit(types.FATAL_ERROR, { err }, { root: true });
    } finally {
        commit(types.FULLSCREEN_LOADING_STOP);
    }
}

Context

I am using babel with webpack 2.2 in a modified vue-webpack template.

package.json
{
  "name": "vista",
  "version": "1.0.0",
  "description": "Front end Single Page Application usin Vue.js for boolean app",
  "author": "Suhas Karanth <[email protected]>",
  "private": true,
  "scripts": {
    "dev": "better-npm-run dev",
    "build": "better-npm-run build",
    "prod": "better-npm-run prod",
    "unit": "better-npm-run unit",
    "e2e": "better-npm-run e2e",
    "test": "npm run unit && npm run e2e",
    "lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs build config",
    "lint:fix": "npm run lint -- --fix",
    "lint-staged": "lint-staged"
  },
  "betterScripts": {
    "dev": {
      "command": "node --debug dev-nodemon.js",
      "env": {
        "NODE_ENV": "development",
        "DEBUG": "vista:*,express:application,express:router:route",
        "DEBUG_DEPTH": 10
      }
    },
    "build": {
      "command": "node build/build.js",
      "env": {
        "NODE_ENV": "production"
      }
    },
    "prod": {
      "command": "node src/app.js",
      "env": {
        "NODE_ENV": "production"
      }
    },
    "unit": {
      "command": "karma start test/unit/karma.conf.js --single-run",
      "env": {
        "NODE_ENV": "testing",
        "BABEL_ENV": "test",
        "DEBUG": "vista:*,express:application,express:router:route",
        "DEBUG_DEPTH": 10
      }
    },
    "e2e": {
      "command": "node test/e2e/runner.js",
      "env": {
        "NODE_ENV": "testing",
        "DEBUG": "vista:*,express:application,express:router:route",
        "DEBUG_DEPTH": 10
      }
    }
  },
  "lint-staged": {
    "src/**/*.{js,vue}": [
      "eslint --fix"
    ],
    "build/*.js": [
      "eslint --fix",
      "git add"
    ],
    "config/*.js": [
      "eslint --fix",
      "git add"
    ],
    "test/**/*.js": [
      "eslint --fix",
      "git add"
    ]
  },
  "pre-commit": "lint-staged",
  "dependencies": {
    "better-npm-run": "0.0.14",
    "debug": "^2.6.0",
    "element-ui": "^1.1.5",
    "express": "^4.14.0",
    "lodash": "^4.17.4",
    "promise-polyfill": "^6.0.2",
    "vue": "^2.1.10",
    "vue-router": "^2.1.3",
    "vue-spinner": "^1.0.2",
    "vuex": "^2.1.1",
    "vuex-router-sync": "^4.1.1",
    "whatwg-fetch": "^2.0.2"
  },
  "devDependencies": {
    "autoprefixer": "^6.4.0",
    "babel-core": "^6.22.1",
    "babel-eslint": "^7.0.0",
    "babel-loader": "^6.0.0",
    "babel-plugin-component": "^0.9.0",
    "babel-plugin-istanbul": "^3.0.0",
    "babel-plugin-lodash": "^3.2.11",
    "babel-plugin-syntax-dynamic-import": "^6.18.0",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-stage-1": "^6.22.0",
    "babel-register": "^6.22.0",
    "chai": "^3.5.0",
    "chalk": "^1.1.3",
    "chromedriver": "^2.21.2",
    "compression-webpack-plugin": "^0.3.2",
    "connect-history-api-fallback": "^1.1.0",
    "cross-spawn": "^5.0.1",
    "css-loader": "^0.26.1",
    "eslint": "^3.7.1",
    "eslint-friendly-formatter": "^2.0.5",
    "eslint-loader": "^1.5.0",
    "eslint-plugin-html": "^2.0.0",
    "eslint-plugin-lodash": "^2.3.2",
    "eslint-plugin-promise": "^3.4.0",
    "eventsource-polyfill": "^0.9.6",
    "extract-text-webpack-plugin": "^2.0.0-rc.0",
    "file-loader": "^0.9.0",
    "friendly-errors-webpack-plugin": "^1.1.2",
    "function-bind": "^1.0.2",
    "html-webpack-plugin": "^2.8.1",
    "http-proxy-middleware": "^0.17.2",
    "inject-loader": "^3.0.0-beta3",
    "karma": "^1.3.0",
    "karma-coverage": "^1.1.1",
    "karma-mocha": "^1.2.0",
    "karma-phantomjs-launcher": "^1.0.0",
    "karma-sinon-chai": "^1.2.0",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-spec-reporter": "0.0.26",
    "karma-webpack": "^2.0.1",
    "lint-staged": "^3.2.8",
    "lodash-webpack-plugin": "^0.11.0",
    "lolex": "^1.4.0",
    "mocha": "^3.1.0",
    "nightwatch": "^0.9.8",
    "nodemon": "^1.11.0",
    "opn": "^4.0.2",
    "ora": "^1.0.0",
    "phantomjs-prebuilt": "^2.1.3",
    "pre-commit": "^1.2.2",
    "selenium-server": "3.0.1",
    "semver": "^5.3.0",
    "shelljs": "^0.7.4",
    "sinon": "^1.17.3",
    "sinon-chai": "^2.8.0",
    "strip-loader": "^0.1.2",
    "url-loader": "^0.5.7",
    "vue-loader": "^10.0.0",
    "vue-style-loader": "^1.0.0",
    "vue-template-compiler": "^2.1.10",
    "webpack": "^2.2.0",
    "webpack-dev-middleware": "^1.8.3",
    "webpack-hot-middleware": "^2.12.2",
    "webpack-merge": "^2.4.0"
  },
  "engines": {
    "node": ">= 6.9.2",
    "npm": ">= 3.10.9"
  }
}
webpack.conf.js
// webpack.base.conf.js
'use strict';

const path = require('path');

const webpack = require('webpack');

const config = require('../config');
const utils = require('./utils');

// check env & config/index.js to decide whether to enable CSS source maps for the
// various preprocessor loaders added to vue-loader at the end of this file

const clientRoot = path.join(appRoot, 'src', 'client');

module.exports = {
    context: appRoot,
    entry: {
        app: './src/client/main.js'
    },
    output: {
        path: config.assetsRoot,
        publicPath: config.assetsPublicPath,
        filename: '[name].js'
    },
    resolve: {
        modules: [
            clientRoot,
            'node_modules',
            path.join(appRoot, 'node_modules')
        ],
        enforceExtension: false,
        extensions: ['.js', '.vue', '.json'],
        alias: {
            // vue$: 'vue/dist/vue.common.js',
            // src: path.join(appRoot, 'src'),
            client: clientRoot,
            assets: path.join(clientRoot, 'assets'),
            lib: path.join(clientRoot, 'lib'),
            components: path.join(clientRoot, 'components'),
            views: path.join(clientRoot, 'views')
        }
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'eslint-loader',
                enforce: 'pre',
                include: [
                    clientRoot
                ],
                exclude: /node_modules/
            },
            {
                test: /\.js$/,
                loader: 'eslint-loader',
                enforce: 'pre',
                include: [
                    clientRoot
                ],
                exclude: /node_modules/,
                options: {
                    formatter: require('eslint-friendly-formatter')
                }
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders: utils.cssLoaders({ sourceMap: config.cssSourceMap, extract: config.extractCss }),
                    postcss: [
                        require('autoprefixer')({
                            browsers: ['last 2 versions', 'ie > 8']
                        })
                    ]
                }
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                include: [
                    clientRoot
                ],
                exclude: /node_modules/
            },
            ...utils.styleLoaders({
                sourceMap: config.cssSourceMap,
                extract: config.extractCss,
                moduleRules: true
            }),
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000,
                    name: utils.assetsPath('img/[name].[hash:7].[ext]')
                }
            },
            {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000,
                    name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
                }
            }
        ]
    },
    plugins: [
        // eslint-disable-next-line no-useless-escape
        new webpack.NormalModuleReplacementPlugin(/element-ui[\/\\]lib[\/\\]locale[\/\\]lang[\/\\]zh-CN/,
        'element-ui/lib/locale/lang/en')
    ]
};

// webpack.dev.conf.js
'use strict';

const _ = require('lodash'),
    webpack = require('webpack'),
    merge = require('webpack-merge'),
    HtmlWebpackPlugin = require('html-webpack-plugin'),
    FriendlyErrors = require('friendly-errors-webpack-plugin');

const config = require('../config'),
    baseWebpackConfig = require('./webpack.base.conf');

// add hot-reload related code to entry chunks
_.forEach(Object.keys(baseWebpackConfig.entry), name => {
    baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]);
});

module.exports = merge(baseWebpackConfig, {
    // eval-source-map is faster for development
    devtool: '#eval-source-map',
    plugins: [
        // https://webpack.js.org/plugins/loader-options-plugin/
        new webpack.LoaderOptionsPlugin({
            debug: false,
            options: {
                context: appRoot
            }
        }),
        new webpack.DefinePlugin({
            'process.env': config.env
        }),
        // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin(),
        // https://github.com/ampedandwired/html-webpack-plugin
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            inject: true
        }),
        new FriendlyErrors()
    ]
});

Your Environment

software version
Babel 6.22.1
node 6.9.4
npm 3.10.10
Operating System ubuntu 16.04

在使用babel-plugin-component的时候,vue jest单元测试失败

`import { shallowMount, createLocalVue } from '@vue/test-utils';

import Vue from 'vue';
import { Button } from 'element-ui';
import Country from '@/components/a.vue';

const localVue = createLocalVue();

localVue.use(Button);

Vue.prototype.$ELEMENT = { size: 'small' };

const wrapper = shallowMount(Country, {
localVue,
propsData: {
visible: true,
},
});

describe('选人组件', () => {
const { vm } = wrapper;
it('currentLeaf', () => {
expect(vm.currentLeaf).toBe(undefined);
});
});`

import 'class' constructor, console ok, but new class is not defined

I'm using babel-plugin-component
here's my import
import {CanvasPoster} from 'ui-lib'
but when I using this: new CanvasPoster()
it says

myPoster.vue?7d2b:33 Uncaught (in promise) ReferenceError: CanvasPoster is not defined

but i can console.log(CanvasPoster)

function CanvasPoster() {
__WEBPACK_IMPORTED_MODULE_3_babel_runtime_helpers_classCallCheck___default()(this, CanvasPoster);

i can fix this problem to change

import CanvasPoster from 'ui-lib/lib/CanvasPoster',

does anyone know why this happen?

多组件引入的时候报错

[
  ["component", {"libraryName": "library1", "styleLibraryName": "styles"}],
  ["component", {"libraryName": "library2", "styleLibraryName": "styles"}]
]
import { component } from "library2"

// 会报 library1/lib/component 找不到

解析的组件对象名不正确

能够重现此问题的测试用例已经提交至 PR #55 ,切换到这个 PR 的分支然后运行 npm test 即可重现:

2019-10-23 15-52-21 的屏幕截图

第一次解析 MessageBox.alert(text) 的结果是正常的:

function alert(text) {
  _messageBox2.default.alert(text);
}

第二次解析 MessageBox.confirm(text) 时 MessageBox 却被解析为 _MessageBox

function confirm(text) {
  return _messageBox.confirm(text);
}

在使用babel-plugin-component做按需引入element-ui,jest单元测试在引入element-ui组件的时候报错

import { shallowMount, createLocalVue } from '@vue/test-utils';

import Vue from 'vue';
import { Button } from 'element-ui'; // 执行到这一行的时候出错
import Country from '@/components/a.vue';


const localVue = createLocalVue();


localVue.use(Button);

Vue.prototype.$ELEMENT = { size: 'small' };


const wrapper = shallowMount(Country, {
  localVue,
  propsData: {
    visible: true,
  },
});

describe('选人组件', () => {
  const { vm } = wrapper;
  it('currentLeaf', () => {
    expect(vm.currentLeaf).toBe(undefined);
  });
});

报错内容如下

image

// babel.config.js
// 当注释掉plugins配置,上述内容才不报错
module.exports = {
  presets: [
    '@vue/app',
  ],
  // plugins: [
  //   [
  //     'component',
  //     {
  //       libraryName: 'element-ui',
  //       styleLibraryName: 'theme-chalk',
  //     },
  //   ],
  // ],
};

我在使用vue的SSR案例时,使用babel,总会把所有插件都打包。

app.js 中没有使用 element-ui 插件

import Vue from 'vue'
import App from './App.vue'
import store from './store'
import router from './router'
import { sync } from 'vuex-router-sync'
import * as filters from './filters'
sync(store, router)

Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})
const app = new Vue({
  router,
  store,
  render: h => h(App)
})
export { app, router, store }

Demo.vue 使用了 Button, Message两个组件

<template>
  <el-button :plain="true" @click="open">打开消息提示</el-button>
</template>

<script>
import Vue from 'vue'
import {
  Button,
  Message
} from 'element-ui'
Vue.use(Button);
Vue.prototype.$message = Message
  export default {
    methods: {
      open() {
        this.$message('这是一条消息提示');
      }
    }
  }
</script>

实际打包 其实把element-ui 所有的代码都打包了,并且 没有样式文件?求教,我该怎么做才能做到按需打包?

.babelrc

{
  "presets": [
    ["es2015", { "modules": false }]
  ],
  "plugins": [["component", [
    {
      "libraryName": "element-ui",
      "styleLibraryName": "theme-default"
    }
  ]]]
}

Uncaught ReferenceError: _MessageBox is not defined

When using with babel@^7.0.0 everything works fine except of the MessageBox-Component of Vue elementUI:

Uncaught ReferenceError: _MessageBox is not defined

main.js:

/*
 * ELEMENT UI
 */
import {
  Alert,
  Button,
  ButtonGroup,
  Card,
  Checkbox,
  CheckboxGroup,
  Col,
  Collapse,
  CollapseItem,
  DatePicker,
  Dialog,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  Form,
  FormItem,
  Input,
  Loading,
  MessageBox,
  Message,
  Option,
  Pagination,
  Radio,
  RadioGroup,
  Row,
  Select,
  Table,
  TableColumn,
  Tag,
  Tooltip,
  Tree,
  Upload
} from 'element-ui'
import lang from 'element-ui/lib/locale/lang/de'
import locale from 'element-ui/lib/locale'

// element-ui localization
locale.use(lang)

Vue.use(Alert)
Vue.use(Button)
Vue.use(ButtonGroup)
Vue.use(Card)
Vue.use(Checkbox)
Vue.use(CheckboxGroup)
Vue.use(Col)
Vue.use(Collapse)
Vue.use(CollapseItem)
Vue.use(DatePicker)
Vue.use(Dialog)
Vue.use(Dropdown)
Vue.use(DropdownItem)
Vue.use(DropdownMenu)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)
Vue.use(Loading)
Vue.use(Option)
Vue.use(Pagination)
Vue.use(Radio)
Vue.use(RadioGroup)
Vue.use(Row)
Vue.use(Select)
Vue.use(Tag)
Vue.use(Table)
Vue.use(TableColumn)
Vue.use(Tooltip)
Vue.use(Tree)
Vue.use(Upload)

Vue.prototype.$msgbox = MessageBox
Vue.prototype.$alert = MessageBox.alert
Vue.prototype.$confirm = MessageBox.confirm
Vue.prototype.$prompt = MessageBox.prompt
Vue.prototype.$message = Message

Nuxt.js中引入按需加载element-ui组件报错

ElementUI version

v1.2.7

babel-plugin-component version

v0.9.1

OS/Browers version

Win7/Chrome57.0.2987.133

Vue version

v2.2.6

Nuxt configuration

nuxt.config.js

// ...
babel: {
  plugins: ['transform-async-to-generator', 'transform-runtime', ['component', [{
    libraryName: 'element-ui',
    styleLibraryName: 'theme-default'
  }]]]
}
// ...

What is actually happening?

 error  in ./~/element-ui/lib/theme-default/date-picker.css

Module build failed: Unknown word (5:1)

  3 | // load the styles
  4 | var content = require("!!../../../css-loader/index.js!./date-picker.css");
> 5 | if(typeof content === 'string') content = [[module.id, content, '']];
    | ^
  6 | if(content.locals) module.exports = content.locals;
  7 | // add the styles to the DOM
  8 | var update = require("!../../../vue-style-loader/lib/addStylesClient.js")("1bb6a9ee", content, false);


 @ ./~/element-ui/lib/theme-default/date-picker.css 4:14-137 13:3-17:5 14:22-145
 @ ./~/babel-loader/lib?{"plugins":["transform-async-to-generator","transform-runtime",["component",[{"libraryName":"element-ui","styleLibraryName":"theme-default"}]]],"presets":["vue-app"],
"cacheDirectory":true}!./~/vue-loader/lib/selector.js?type=script&index=0!./pages/index.vue
 @ ./pages/index.vue
 @ ./.nuxt/router.js
 @ ./.nuxt/index.js
 @ ./.nuxt/client.js
 @ multi webpack-hot-middleware/client?reload=true ./.nuxt/client.js

 error  in ./~/element-ui/lib/theme-default/base.css

Module build failed: Unknown word (5:1)

  3 | // load the styles
  4 | var content = require("!!../../../css-loader/index.js!./base.css");
> 5 | if(typeof content === 'string') content = [[module.id, content, '']];
    | ^
  6 | if(content.locals) module.exports = content.locals;
  7 | // add the styles to the DOM
  8 | var update = require("!../../../vue-style-loader/lib/addStylesClient.js")("7011cd8e", content, false);


 @ ./~/element-ui/lib/theme-default/base.css 4:14-130 13:3-17:5 14:22-138
 @ ./~/babel-loader/lib?{"plugins":["transform-async-to-generator","transform-runtime",["component",[{"libraryName":"element-ui","styleLibraryName":"theme-default"}]]],"presets":["vue-app"],
"cacheDirectory":true}!./~/vue-loader/lib/selector.js?type=script&index=0!./pages/index.vue
 @ ./pages/index.vue
 @ ./.nuxt/router.js
 @ ./.nuxt/index.js
 @ ./.nuxt/client.js
 @ multi webpack-hot-middleware/client?reload=true ./.nuxt/client.js

麻烦您帮我看看是不是哪里配置错了?

修改父节点选中事件,子节点不会触发自己的选中事件

在默认父节点不展开的情况下,点击父节点的checkbox,只有父节点触发了handleCheckChange事件,子节点并不会触发handleCheckChange事件
在el-tree中添加了@check-change="handleCheckChange",
看了下在刷新页面或者mounted之后,子节点并没有渲染到dom当中,请问,为何这么设计?
当需要子节点触发handleCheckChange,其实并没有。

style is not importing

.babelrc

{
  "presets": [
    ["es2015", { "modules": false }]
  ],
  "plugins": [["component", [
    {
      "libraryName": "mint-ui",
      "style": true
    }
  ]]]
}

main.js

import Vue from 'vue';
import App from './app';

import { Checklist } from 'mint-ui';
Vue.component(Checklist.name, Checklist);

new Vue({ // eslint-disable-line
  el: '#app',
  render: h => h(App)
});

project scaffolded with cooking

在laravel里的elixir怎么配置?

` Elixir.webpack.mergeConfig({
resolveLoader: {
root: path.join(__dirname, 'node_modules'),
},
babel: {
presets: ["es2015", {
"modules": false
}],
plugins: ["component", [{
"libraryName": "element-ui",
"styleLibraryName": "theme-default"
}]]

    },
    module: {
        loaders: [{
            test: /\.css$/,
            loader: 'style!css'
        }]
    }
    

});`

我这样配置没用,压出来还是一样大

不支持 for of

Error:

项目中有一个 js 文件中使用了 for of, 在编译的时候报如下错误:

Module build failed: basic.js: Cannot read property 'name' of null
at node_modules/babel-plugin-component/lib/core.js:195:33

Code:

for (const mod of modules) {
    console.log(mod)
}

modules 是一个数组

我使用的babel-plugin-import 0.4.2 版本, 经测试, 0.6.0 也存在这个问题
for of改为:

for (let i = 0; i < modules.length; i++) {}

后正常.

Thanks

怎么动态使用babel-plugin-component这个插件

如题,我近期用到了elementui,因为觉得很好用,就把我之前项目整个替换成该UI库,但是现在遇到一个问题,希望各位大大给点帮助,因为网络上实在没有找到相关问题。
我的项目里有两个入口文件,index.js和login.js,对应两个html。
因为登录页只用到少许组件,所以我就想在login页使用babel-plugin-component这个插件,但index.js里是照常引入。
import Vue from 'vue';
import ElementUI from 'element-ui';
Vue.use(ElementUI);
这个时候babel-plugin-component就会报错
ERROR in ./src/app.js
Module build failed: Error: C:/Users/kuo/Desktop/vue-projects/gk/src/app.js: [babel-plugin-component] If you are using bothon-demand and importing all, make sure to invoke the importing all first.
at importMethod (C:\Users\kuo\Desktop\vue-projects\gk\node_modules\babel-plugin-component\lib\core.js:103:21)

请问有什么配置或方法是可以动态使用babel-plugin-component这个插件的吗?感激不尽。

element-ui 按需导入 样式文件丢失

vue 版本 2.6
element 版本 2.15
vue-cli 版本 4.5.17
babel.config.js 配置文件

{
  "presets": [
    "@vue/cli-plugin-babel/preset"
   ],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

组件正常按需加载,但是样式缺失,如果加载全局css文件样式正常,但是理论上来讲应该会自动按需加载css的

import { DatePicker } from 'element-ui' ,但没有import date-picker 样式文件,样式出不来

已经配置好 babel-plugin-component, build后 js文件从 936KB缩小到 367KB。但是样式文件没有缩小。
我想是因为我的代码把样式全部引入 import 'element-ui/lib/theme-chalk/index.css'
把这句去掉又会没有样式,可是README不是说了

Converts

import { Button } from 'components'
to

var button = require('components/lib/button')
require('components/lib/button/style.css')

那按说不需要再引入样式了啊 ?
请问到底要如何 按需引入组件的样式文件 ?

同时按需引入两个组件,官方的配置报错,如何配置

按照这样子配置
{
"plugins": [xxx,
["component", {
libraryName: "antd",
style: true,
}, "antd"],
["component", {
libraryName: "test-module",
style: true,
}, "test-module"]
]
}
跑起来就报错了,
修改成{
"plugins": [xxx,
["component", {
libraryName: "antd",
style: true,
}, {
libraryName: "test-module",
style: true,
}]
]
}
跑起来没有问题,但打包后发现第二个“test-module”组件库的按需引入没有起到作用,即使按需引入也引入了整个包。
求大神帮解决哈

同一个项目中,既包含了全量引入,又包含了按需引入,然后有如下报错,请教下如何解决?

error in ./src_form/main.js

Syntax Error: Error: D:\Project\jc_forms_git\src_form\main.js: [babel-plugin-component] If you are using bothon-demand and importing all, make sure to invoke the importing all first.
at Array.map ()

@ multi (webpack)-dev-server/client?http://192.168.1.208:8080/sockjs-node (webpack)/hot/dev-server.js ./src_form/main.js

error in ./src_report/main.js

Syntax Error: Error: D:\Project\jc_forms_git\src_report\main.js: [babel-plugin-component] If you are using bothon-demand and importing all, make sure to invoke the importing all first.
at Array.map ()

@ multi (webpack)-dev-server/client?http://192.168.1.208:8080/sockjs-node (webpack)/hot/dev-server.js ./src_report/main.js

error in ./src_todo/main.js

Syntax Error: Error: D:\Project\jc_forms_git\src_todo\main.js: [babel-plugin-component] If you are using bothon-demand and importing all, make sure to invoke the importing all first.
at Array.map ()

@ multi (webpack)-dev-server/client?http://192.168.1.208:8080/sockjs-node (webpack)/hot/dev-server.js ./src_todo/main.js

Question : Can I change CSS colors dynamically?

Hi,

My client is asking me to allow users to create their own Blog-like pages on our platform. These blogs should all look different, and one of the demands is to allow users to change the colors of the elements on the page (buttons, text, header, ...). Could it be possible to load the styles but change the colors according to the color selected by the user when using babel-plugin-component?

Thanks.

Xavier

组件样式覆盖问题

按需引入的css样式优先级太高了,无论在App.vue还是main.js中引入用来覆盖的css样式,都不能产生效果。发现组件的<style>在比较靠前的位置,直接在index.html<body>中引入样式可以处理覆盖问题,但是这样只能引入.css,就不能用预处理器了,有什么更好的办法吗?

babel-plugin-component 按需引入报错,没有找到 base.css 文件

自己写了个仿 element-ui 的小 demo,去实现按需引入,可是在测试项目里使用 babel-plugin-component,遇到报错

image

下面是我的相关文件:
测试项目相关:

import { Button } from 't-element-ui'
Vue.use(Button)
# For babel6
npm i babel-plugin-component@0 -D

package.json
image

.babelrc:
image

仿 element-ui demo:

image

以上会报错。但按照文档说明来看,应该没有 base.css 文件就不会自动生成引入 base.css
image

解决办法是,手动增加 base.css 文件。我给了个空文件。最后解决了报错。
image

所以问题是,demo 里没有 base.css,却会有引用报错。

使用 jsx 时按需加载的问题

代码:

import Vue from 'vue'
import { Button } from 'element-ui'
console.log(Button)
export default Vue.extend({
    render: function (h) {
        return <Button>Hello element-ui</Button>
    }
})

webpack 输出:

/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_element_ui_lib_theme_default_button_css__ = __webpack_require__(18);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_element_ui_lib_theme_default_button_css___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_element_ui_lib_theme_default_button_css__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_element_ui_lib_theme_default_base_css__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_element_ui_lib_theme_default_base_css___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_element_ui_lib_theme_default_base_css__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_element_ui_lib_button__ = __webpack_require__(16);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_element_ui_lib_button___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_element_ui_lib_button__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_vue__ = __webpack_require__(1);

console.log(__WEBPACK_IMPORTED_MODULE_2_element_ui_lib_button___default.a);
/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_3_vue__["default"].extend({
    render: function (h) {
        return h(
            Button,
            null,
            ['Hello element-ui']
        );
    }
}));

浏览器控制台输出:
image

babelrc:

{
    "presets": [],
    "plugins": [
        "transform-vue-jsx",
        ["component",[{
                    "libraryName": "element-ui",
                     "styleLibraryName": "theme-default"
        }]]]
}

webpack版本: 2.4.1

是否可以同时支持mint-ui和element-ui

.babelrc

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "browsers": [
            "> 1%",
            "last 2 versions",
            "not ie <= 8"
          ]
        },
        "modules": false,
        "useBuiltIns": true,
        "debug": false
      }
    ],
    "es2015",
    "stage-2"
  ],
  "plugins": [
    "transform-vue-jsx",
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ],
    [
      "component",
      [
        {
          "libraryName": "mint-ui",
          "style": true
        }
      ]
    ]
  ]
}

ImportSpecifier 中 有local Identifier的时候报错

import { Container as ElContainer } from 'element-ui'

这样会报错,这样对于JSX单文件组件或者class-component 很不方便。

需要多写Vue的组件注册(其实完全可以省掉)

Vue.component(Container.name, Container);

或者比如现在的形式,需要在components中alias一下。

import { Container, Main, Button, Header } from 'element-ui'
import template from './app.vue'

@Component({
    name: 'page-app',
    mixins: [template],
    components: {
        ElContainer: Container
    }
})
export default class App extends Vue {

}

或者单文件组件

import { Container, Main, Button, Header } from 'element-ui'
const ElContainer = Container 
@Component({
    name: 'page-app'
})
export default class App extends Vue {
   render () {
       <ElContainer/>
  }
}

极其不方便。

按需引入官方问题配置出错

第一个问题
Error: Cannot find module 'babel-preset-es2015'
Require stack:
- F:\vue\dev\dev\node_modules@babel\core\lib\config\files\plugins.js
- F:\vue\dev\dev\node_modules@babel\core\lib\config\files\index.js
- F:\vue\dev\dev\node_modules@babel\core\lib\index.js
- F:\vue\dev\dev\node_modules@vue\cli-plugin-babel\index.js
- F:\vue\dev\dev\node_modules@vue\cli-service\lib\Service.js

第二个问题
Error: .plugins[0][1] must be an object, false, or undefined
Error: .plugins[0][1] must be an object, false, or undefined
at validate (F:\vue\dev\dev\node_modules@babel\core\lib\config\validation\options.js:86:25)
at F:\vue\dev\dev\node_modules@babel\core\lib\config\config-chain.js:165:34
at cachedFunction (F:\vue\dev\dev\node_modules@babel\core\lib\config\caching.js:48:27)
at cachedFunction.next ()
at evaluateSync (F:\vue\dev\dev\node_modules\gensync\index.js:251:28)
at sync (F:\vue\dev\dev\node_modules\gensync\index.js:89:14)
at buildRootChain (F:\vue\dev\dev\node_modules@babel\core\lib\config\config-chain.js:77:27)
at buildRootChain.next ()
at loadPrivatePartialConfig (F:\vue\dev\dev\node_modules@babel\core\lib\config\partial.js:79:62)
at loadPrivatePartialConfig.next ()

旧配置项
{
"presets": [["es2015", { "modules": false }]],
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}

大佬们能不能改改官方文档,按需文档一步步走真的出错,不好找原因

部分模块不含样式,插件会自动索引样式文件导致报错

在使用vux时,自定义了libDir,能够简洁方便低导入需要的组件,但是对于vux的子组件,由于编译产出的dist目录里对应的子组件不含css样式文件,导致node导入模块失败。
请问能不能做到遍历对应模块目录,根据是否包含样式文件,再导入样式模块呢?

path.hub is undefined

In src/core.js, you do const { file } = path.hub, in my situation, the path.hub may be undefined, so that webpack throw errors. I didn't find any document about what the keys of path stands for, such as hub, data and so on. I'm trying to find out the reason and need help.

更新wp4后, 构造器被转码导致报错

Error in event handler for "el.form.blur": "TypeError: _asyncValidator2.default is not a constructor"

`methods: {
validate: function validate(trigger) {
var _this = this;

  var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _util.noop;

  this.validateDisabled = false;
  var rules = this.getFilteredRule(trigger);
  if ((!rules || rules.length === 0) && this.required === undefined) {
    callback();
    return true;
  }

  this.validateState = 'validating';

  var descriptor = {};
  if (rules && rules.length > 0) {
    rules.forEach(function (rule) {
      delete rule.trigger;
    });
  }
  descriptor[this.prop] = rules;

  var validator = new _asyncValidator2.default(descriptor);
  var model = {};

  model[this.prop] = this.fieldValue;

  validator.validate(model, { firstFields: true }, function (errors, invalidFields) {
    _this.validateState = !errors ? 'success' : 'error';
    _this.validateMessage = errors ? errors[0].message : '';

    callback(_this.validateMessage, invalidFields);
    _this.elForm && _this.elForm.$emit('validate', _this.prop, !errors);
  });
},
clearValidate: function clearValidate() {
  this.validateState = '';
  this.validateMessage = '';
  this.validateDisabled = false;
},`

var validator = new _asyncValidator2.default(descriptor); 这句的转码有问题.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.