我将使用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
。换句话说,你需要在webpack操作中包含sample1.js
才能使其正常工作。 - user5734311typescript
编写的,所以我必须通过ts
而不是webpack进行转换!@ChrisG - Mohammad Dayyants
命令来转换我的typescript文件,我添加了我的webpack配置。 - Mohammad Dayyanimport
和export
。这里是如何做到的:https://dev59.com/yFYM5IYBdhLWcg3w5zUg#48212558 要明确一点:你不能同时做两者。 - user5734311