我正在尝试在我的项目中使用 imagemin 节点包。它是一个 es6 模块,我在使用它时遇到错误。
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module.
在 package.json 中将“类型”作为“模块”
ReferenceError: require is not defined
package.json 中的“type”为“commonjs”
我的 webpack 配置:
export default env => {
return {
mode: env.production ? 'production' : 'development',
entry: {
main: './src/main.ts',
worker: './src/worker.ts'
},
target: ['node', 'es2019'],
devtool: env.production ? false : 'inline-source-map',
watch: !env.production,
resolve: {
extensions: ['.ts', '.js'],
alias: {
src: _resolve(process.cwd(), './src')
}
},
module: {
rules: [{
test: /\.ts$/,
include: _resolve(process.cwd(), "src"),
use: 'ts-loader',
exclude: [/node_modules/, /\.spec\.ts/, /\.e2e-spec\.ts/]
}],
},
externalsPresets: { node: true },
externals: [nodeExternals()],
output: {
filename: '[name].js',
path: OUTPUT_DIR,
clean: !!env.production,
devtoolModuleFilenameTemplate: 'file:///[absolute-resource-path]',
library: {
type: 'module'
}
},
optimization: {
minimize: false, //!!env.production
mangleExports: true,
minimizer: [new terserPlugin({
terserOptions: {
output: {
comments: false
},
keep_classnames: true,
},
extractComments: false,
})]
},
experiments: {
outputModule: true
}
};
};
我的 tsconfig:
{
"compilerOptions": {
"module": "ES2020",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2019",
"sourceMap": true,
"strict": true,
"baseUrl": ".",
"esModuleInterop": true,
"noImplicitAny": true,
"moduleResolution": "node",
"outDir": "../bin/server",
"typeRoots": [
"node_module/@types",
"./typings"
],
"types": [
"node",
"@types/jest"
]
},
"exclude": [
"node_modules"
]
}
当我尝试在我的一个 .ts 文件中“导入”imagemin 时,webpack 将其转换为“require”。我也尝试过使用import()
,但它也不起作用。我在github上做了一个repo
有没有办法获得 es6 包(首选)或将 imagemin 与 commonjs 包一起使用?