【问题标题】:Unable to import module after bundling with web pack与 web pack 捆绑后无法导入模块
【发布时间】:2018-02-21 08:33:06
【问题描述】:

我有以下 index.js 代码:

import {Asp} from './src/asp.js';

export default Asp;

以及以下 run.js 代码:

import Asp from './dist/bundle.js'; // Uncaught SyntaxError: The requested module does not provide an export named 'default'
import Asp from './index.js'; // works

const myASP = new Asp();

和 webpack (3.11) 配置文件:

const path = require('path');

module.exports = {
    entry: './index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
        ]
    }
};

我不明白为什么在我导入时使用 bundle.js 不起作用...帮助...

更新:

我放弃了 webpack,转而使用以下配置解决了我的问题:

import uglify from 'rollup-plugin-uglify';

export default {
    input: 'src/index.js',
    output:{
        file: 'dist/index.js',
        name: 'Asp',
        format: 'es'
    },
    plugins: [
        uglify()
    ]
}

我不知道在 webpack 中有什么相当于 this - 但它完成了工作!

【问题讨论】:

  • 为什么要在导入之前捆绑它?通常你只会在最后捆绑它。
  • loganfsmyth - 你是什么意思?我不明白你的评论。
  • 为什么你有一个run.js 来导入bundle.js,而不是让run.js 在你的webpack 配置中成为entry?然后你根本不会导入包,只需将它作为一个整体运行。
  • Loganfsmyth - 我使用 run.js 只是为了测试 'Asp' 作为一个模块。就像“Asp”是您可以导入任何项目的第 3 方对象一样。
  • 我很困惑。你说import Asp from './index.js'; // works,所以我假设你有第二个设置来实际处理这些导入,但是你现在看到的SyntaxError: Unexpected token import 错误是因为这些导入,而不是因为 Webpack。您的意思是让run.js 使用require

标签: webpack ecmascript-6


【解决方案1】:

默认情况下,Webpack 输出一个 Script 文件,这意味着它没有导出,因此尝试将其导入另一个文件不会产生任何结果。

要告诉 Webpack 将包输出为可重用库,您需要告诉它使用 output.libraryTarget 执行此操作,因此您可能需要调整

output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
},

成为

output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    libraryTarget: 'commonjs2'
},

【讨论】:

  • 没用。 :( 我不断收到相同的“未捕获语法错误”错误消息
  • 请包含完整的错误信息,如果没有它真的很难诊断:)
  • 我在这里放了一个小例子:github.com/kfirm/thirdPartyModuleTest
  • 这对我有用。在此更改之前,我在导入库时总是得到一个空对象。
【解决方案2】:

在 index.js 文件中,您只需要导入 Asp,并删除导出行。所以 index.js 文件将是:

import {Asp} from './src/asp.js';

在 run.js 中

import {Asp} from './dist/bundle.js'; 

const myASP = new Asp();

【讨论】:

  • 没用 :(。得到“Uncaught SyntaxError: The requested module does not provide an export named 'Asp'”
  • 你在 asp.js 中导出了什么?
  • 导出类 Asp {}
猜你喜欢
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2019-09-23
相关资源
最近更新 更多