【问题标题】:Force Webpack 4 to import cjs only and never esm with typescript强制 Webpack 4 仅导入 cjs 而从不使用打字稿 esm
【发布时间】:2021-11-18 20:16:19
【问题描述】:

基于webpack@4.43.0 构建的应用程序;打字稿 4.2.4;

尝试在应用上安装和使用@reduxjs/toolkit 会产生构建错误:

ERROR in ./node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js
Module not found: Error: Can't resolve 'immer' in './node_modules/@reduxjs/toolkit/dist'

如何禁用从库 package.json 的“模块”路径导入 esm 模块并在 webpack 中仅使用“主”入口点?

@reduxjs/toolkit的package.json

  "main": "dist/index.js",
  "module": "dist/redux-toolkit.esm.js",
  "unpkg": "dist/redux-toolkit.umd.min.js",
  "types": "dist/index.d.ts",

我们的配置: tsconfig.json

    "target": "es6",
    "jsx": "react",
    "module": "commonjs",
    "lib": [
      "es6",
      "dom",
      "esnext",
      "esnext.asynciterable"
    ],
    "strict": true,
    "sourceMap": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,

webpack.config.js

const HappyPackConfig = new HappyPack({
  id: 'ts',
  threads: 2,
  loaders: [
    {
      path: 'ts-loader',
      query: { happyPackMode: true },
      options: {
        transpileOnly: true,
      },
    },
  ],
});

module.exports = {
  node: {
    net: 'mock',
  },
  entry: ['whatwg-fetch', './src/index.tsx'],
  output: {
    path: path.resolve('dist'),
    filename: '[name].bundle.[contenthash].js',
    publicPath: '/',
    globalObject: 'this',
  },
  devtool: process.env.NODE_ENV === 'development' ? 'inline-source-map' : false,
  devServer: {
    https: true,
    historyApiFallback: true,
    watchOptions: {
      ignored: /node_modules/,
    },
  },
  optimization: { ... },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /\/node_modules/,
        use: { loader: 'happypack/loader?id=ts' },
      },
    ],
  },
};

package.json 不包含"type": "module" 而且我们没有使用babel

【问题讨论】:

    标签: typescript webpack package.json redux-toolkit tsconfig


    【解决方案1】:

    将以下参数添加到 webpack.config.js 对我来说有帮助:

    module.exports = {
    /* ... */
    resolve: {
        /* ... */
        mainFields: ['browser', 'main'],
      },
    };
    

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 2023-02-07
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2019-10-24
      • 2017-03-11
      • 2022-11-12
      相关资源
      最近更新 更多