繁体   English   中英

如何将带有Webpack和Babel的ES6类导出到AMD

[英]How to export a ES6 class with Webpack and Babel to AMD

我正在尝试在ES6中编写一个类,并将其作为Babel(并与jQuery捆绑在同一文件中)作为AMD模块作为AMD模块转换为一个库,以便人们可以这样使用:

<script src="Foo.js"></script>
<script>
    var dummy = new Foo();
</script>

我在这里按照解决方案进行操作并按以下方式排列我的文件夹:

-dist
-js
  |--Foo.js
  |--main.js
-lib
  |--jquery.js
-node_modules
-webpack.config.js
-.babelrc
-.eslintrc
-package.json

Foo.js

import $ from '../lib.jquery.js';

export default class Foo {
    constructor(){
        /* jQuery stuff */
    }
}

main.js

module.exports = require('./Foo.js').default;

webpack.config.js

require('babel-polyfill');
const path = require('path');
const webpack = require('webpack');

module.exports = {
    name: "bundle-js",
    entry: {
        Foo: [
            // configuration for babel6
            'babel-polyfill',
            './js/main.js'
        ]
    },
    output: {
        path: path.resolve(__dirname, 'dist'),  // ./build
        filename: '[name].bundle.js',
        library: 'Foo',
        libraryTarget: 'umd'
    },
    module: {
        rules: [{
            test: /\.js$/,
            loader: ['babel-loader', 'eslint-loader'],
            exclude: /node_modules/,
        }]
    },
    stats: {
        colors: true
    },
    devtool: 'source-map'
};

.babelrc

{
    "plugins": ["transform-es2015-modules-amd"],
    "presets": ["react", "es2015","stage-0"]
}

而且我一直收到这个错误:

js/main.js: Property object of MemberExpression expected node to be of a type ["Expression"] but instead got null

有人可以帮助我,告诉我哪里出了问题,以便我解决它? 我更偏爱AMD,因此,如果有人拥有使用CommonJS的解决方案并且执行相同的操作,那么我会接受的。

编辑:为避免分心,此问题与Webpack无关,因为我使用了命令babel --presets es2015 --plugins transform-es2015-modules-amd js/main.js -o dist/Foo.bundle.js和仍然有相同的错误。

这是AMD变压器插件的问题,您要尝试包含的用途require它无法处理。 对细节github上的问题。 请改用UMD插件,尤其是因为您说要将此作为库发布时。

我不知道您的问题是什么,但我的方法如下:

通过npm安装jquery

npm i jquery;

然后配置webpack.conf

resolve: {
    alias: {
        $: "jquery",
        jQuery: "jquery",
    },
...
// for jquery plugins
new webpack.ProvidePlugin({
   'jQuery': 'jquery',
   'window.jQuery': 'jquery',
   'window.$': 'jquery',
}),

...

并导入jQuery

import $ from 'jquery';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM