【问题标题】:How to include imported class in bundle, when not directly used不直接使用时如何在包中包含导入的类
【发布时间】:2020-01-22 23:40:27
【问题描述】:

我正在编写我自己的 JSX pragma,它确实工作得很好,除了现在要引入 typescript JSX 对我不起作用。我的班级正在被摇树或其他什么,除非它正在模块中积极使用,例如在日志语句中:

/** @jsx V.create */
/** @jsxFrag V.Fragment */
import V, { render } from "@V"; // `@V` is in a webpack resolve.alias

render(document.getElementById("app"), <h1>hi</h1>);

external "V":1 Uncaught ReferenceError: V is not defined

但是,

/** @jsx V.create */
/** @jsxFrag V.Fragment */
import V, { render } from "@V"; // `@V` is in a webpack resolve.alias
console.log({ V })
render(document.getElementById("app"), <h1>hi</h1>);

^^ Works!

相关的 webpack 对象:

{
  test: /\.(js|jsx|ts|tsx)$/,
  exclude: /node_modules/,
  use: {
    loader: "babel-loader"
  }
}

tsconfig.json

{
  "include": ["src/**/*"],
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "esnext",
    "jsx": "react",
    "declaration": true,
    "sourceMap": true
  },
  "baseUrl": "src",
  "paths": {
    "@V": ["js/V/index.ts"]
  }
}

如何确保 Webpack/Typescript 不会删除此导入?

【问题讨论】:

    标签: javascript typescript webpack ecmascript-6 jsx


    【解决方案1】:

    您需要为模块 V 禁用 tree shacking。

    您可以使用 sideEffects 数组来禁用摇树

    Here the documentation of WebPack

    在你的 package.json 文件中

    {
      "name": "your-project",
      "sideEffects": [
        "./src/some-side-effectful-file.js"
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-31
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 2019-06-09
      • 2023-04-06
      • 2019-03-17
      相关资源
      最近更新 更多