【问题标题】:Building es6 module in typescript project with webpack使用 webpack 在 typescript 项目中构建 es6 模块
【发布时间】:2021-09-04 19:36:59
【问题描述】:

我正在尝试在我的项目中使用 imagemin 节点包。它是一个 es6 模块,我在使用它时遇到了错误。

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module. 在 package.json 中将“type”作为“module”

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做了一个回购

有没有办法获取 es6 包(首选)或将 imagemin 与 commonjs 包一起使用?

【问题讨论】:

    标签: node.js typescript webpack es6-modules javascript-import


    【解决方案1】:

    我找不到通过 webpack 捆绑 es6 格式的方法,但我能够在通过 webpack 捆绑时在 commonjs 系统中使用 es6 模块。

    externals: [
               nodeExternals({
                   allowlist: ['imagemin', 'imagemin-mozjpeg']
               }),
               async function ({ request }) {
                   if (request === 'imagemin' || request === 'imagemin-mozjpeg')
                       return `import ${request}`;
               },
           ]
    

    这就是我让 imagemin 工作的方式。

    【讨论】:

      【解决方案2】:

      更改你的启动脚本

         "start": "node --experimental-modules src/index.mjs "
      

      并在 package.json 中添加

      { 
         ...
         "type": "module",
         ...
      }
      

      【讨论】:

      • --experimental-modules 不再需要。
      • 问题表明它在package.json中已经有"type": "module"
      • 在 package.json 中将“类型”作为“模块”。我收到错误 ReferenceError: require is not defined.
      • 当 package.json 文件中有 'type: module' 时,你的源代码应该使用import 语法。当你没有时,你应该使用require 语法。将'type': 'module' 添加到package.json 可以启用ES 6 模块。有关详细信息,请参阅here
      • 是的,我了解 package.json 中的 type 是如何工作的,问题是 webpack。我无法让它输出 es6 模块。
      猜你喜欢
      • 2019-02-01
      • 2018-02-05
      • 2019-10-09
      • 2020-08-31
      • 2017-06-17
      • 2016-05-03
      • 2017-10-07
      • 1970-01-01
      • 2016-02-28
      相关资源
      最近更新 更多