请求的模块未提供名为webpack的导出?

4

我将使用typescript编写一个模块,然后使用webpack 5将其转换为js。
我的ES模块非常简单
my.module.ts如下所示:

export class SampleModule {
  constructor(element: Element) {
    this.el = element;
  }

  private el: Element;

  logElement(): void {
    console.log(this.el);
  }
}

通过webpack 5生成的js

(()=>{"use strict";!function(){function t(t){this.el=t}t.prototype.logElement=function(){console.log(this.el)}}()})();

当我想要使用它时:

<body>
  <div class="container">

  </div>
  <script type="module" src="sample1.js"></script>
</body>

samle1.js

import { SampleModule } from '../dist/sample.js'
new SampleModule(document.querySelector('[data-name="dtp1"]'));

但是我遇到了以下错误。
Uncaught SyntaxError: The requested module '../dist/sample.js' does not provide an export named 'SampleModule'

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');

module.exports = {
  entry: {
    'sample': './src/sample.ts'    
  },
  devtool: 'source-map',
  mode: 'production',
  module: {
    rules: [{
      test: /\.tsx?$/,
      use: 'ts-loader',
      exclude: /node_modules/,
    }, {
      test: /.s?css$/,
      use: [{
          loader: MiniCssExtractPlugin.loader,
          options: {}
        },
        'css-loader'
      ],
    }],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  externals: {
    bootstrap: 'bootstrap',
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true
  },
  watch: false,
  devServer: {
    lazy: false,
    watchContentBase: true
  },
  optimization: {
    minimizer: [
      new TerserPlugin({
        extractComments: false,
      }),
      new CssMinimizerPlugin(),
    ],
  },
  plugins: [
    new RemoveEmptyScriptsPlugin(),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    }),
    new webpack.BannerPlugin({
      banner: `
version : 4.0.0
      `
    })
  ]
};

你试过导出默认的类SampleModule吗? - dee
1
我认为你不能以这种方式使用webpack;你应该有一堆带有import和export语句的模块,然后使用webpack将它们合并成一个单独的脚本。正如你在生成的输出中所看到的,没有任何地方出现SampleModule。换句话说,你需要在webpack操作中包含sample1.js才能使其正常工作。 - user5734311
我的模块是用typescript编写的,所以我必须通过ts而不是webpack进行转换!@ChrisG - Mohammad Dayyan
我不明白。你的问题说“然后我使用webpack 5将其转换为js。” - user5734311
我通过webpack 5而不是直接使用ts命令来转换我的typescript文件,我添加了我的webpack配置。 - Mohammad Dayyan
1
再说一遍:webpack在这里不是合适的工具。再说一遍:webpack用于将一堆模块编译成一个单独的脚本。相反,你想要做的是在浏览器中使用模块,这是最近才可能的(这也是为什么创建了webpack)。然而,现在你可以在浏览器中使用importexport。这里是如何做到的:https://dev59.com/yFYM5IYBdhLWcg3w5zUg#48212558 要明确一点:你不能同时做两者 - user5734311
1个回答

2

经过一些谷歌搜索,我解决了这个问题:
请注意以下部分:

module: {
 rules:[
 .
 .
 .
   use: [{
     loader: 'expose-loader',
     options: {
      exposes: ['myNameSpace'],
     },
    }, {
      loader: 'ts-loader'
    }]
 .
 .
 .
 ]
}

webpack.config.js 完整版:

const path = require('path');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');

module.exports = {
  entry: {
    'sample': './src/sample.ts'
  },
  devtool: 'source-map',
  mode: 'production',
  module: {
    rules: [{
      test: /\.tsx?$/,
      use: [{
        loader: 'expose-loader',
        options: {
          exposes: ['myNameSpace'],
        },
      }, {
        loader: 'ts-loader'
      }],
      exclude: /node_modules/,
    }, {
      test: /.s?css$/,
      use: [{
          loader: MiniCssExtractPlugin.loader,
          options: {}
        },
        'css-loader'
      ],
    }],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  externals: {
    bootstrap: 'bootstrap',
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true
  },
  watch: false,
  devServer: {
    lazy: false,
    watchContentBase: true
  },
  optimization: {
    minimizer: [
      new TerserPlugin({
        extractComments: false,
      }),
      new CssMinimizerPlugin(),
    ],
  },
  plugins: [
    new RemoveEmptyScriptsPlugin(),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    }),
    new webpack.BannerPlugin({
      banner: `
version : 4.0.0
      `
    })
  ]
};

现在我们可以像下面这样使用捆绑的JavaScript文件:

将JavaScript添加到HTML中:

<script src="sample1.js" type="text/javascript"></script>

JavaScript文件:

new myNameSpace.SampleModule(document.querySelector('[data-name="dtp1"]'));

@Dayyan 这个命名空间的解决方法不错,但你有没有发现是否可以使用export关键字?并且使用import ... from ... bundle.js - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接