簡體   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