【问题标题】:Webpack compile export from ts file into nothingWebpack 将 ts 文件中的导出编译成空
【发布时间】:2021-03-22 22:09:14
【问题描述】:

我的 index.ts 文件中只有一行。

export * from "./foo"

foo.ts 文件中也只有一行。

export const foo = ()=> 'bar'

我只使用“npx webpack-cli init”中的默认配置。 仅编辑“模式”和“输出”。

const TerserPlugin = require('terser-webpack-plugin');


module.exports = {
  mode: 'production',
  entry: './src/index.ts',
  output:{
    filename:'index.js'
  },
  plugins: [new webpack.ProgressPlugin()],

  module: {
    rules: [{
      test: /\.(ts|tsx)$/,
      loader: 'ts-loader',
      include: [path.resolve(__dirname, 'src')],
      exclude: [/node_modules/],
      options:{
        transpileOnly: true
      }
    }]
  },

  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },

  optimization: {
    minimizer: [new TerserPlugin()],

    splitChunks: {
      cacheGroups: {
        vendors: {
          priority: -10,
          test: /[\\/]node_modules[\\/]/
        }
      },

      chunks: 'async',
      minChunks: 1,
      minSize: 30000,
      name: false
    }
  },
  target:"web"
}

这是我的 tsconfig.js

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": false,
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "allowJs": false,
    "sourceMap": true
  }
}

这是我的 package.json

{
  "name": "npm",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@webpack-cli/init": "^1.0.3",
    "babel-plugin-syntax-dynamic-import": "^6.18.0",
    "terser-webpack-plugin": "^5.0.3",
    "ts-loader": "^8.0.12",
    "typescript": "^4.1.2",
    "webpack": "^5.10.0",
    "webpack-cli": "^4.2.0"
  }
}

当我运行构建时使用这些

"build": "webpack"

我在“dist/index.js”中有一个空的 index.js。 我错过了什么?

【问题讨论】:

  • 当我用 typescript "tsc" 编译时没问题
  • 你也可以分享你的package.json吗?
  • 我编辑了问题以包含 package.json
  • @tmhao2005 希望对您有所帮助

标签: javascript typescript npm webpack export


【解决方案1】:

我认为问题在于要删除未使用的webpack 导出。请记住,webpack 能够执行此操作,除非传递给它的输入代码必须是 esm 样式,就像您通过配置的 module: "es6" 所做的一样。

在导出为库的情况下,您可能必须通过指定目标来告诉 webpack 构建为库,甚至可以添加名称:

webpack.config.js

{
  output: {
    library: "yourLibName",
    libraryTarget: "umd",
    filename: "index.js"
  },
}

【讨论】:

  • 我的代码将在浏览器环境中使用。我认为 commonjs 适用于节点环境。换成“commonjs”会不会有问题?
  • 不。 commonjs 将被传递给 webpack 然后它实际上将被转换为支持在浏览器上运行的代码
  • 谢谢。使用 commonjs,index.js 文件不再为空。但我无法在浏览器环境中从中导入。
  • 你能具体告诉我你想达到什么目标吗?
  • 可以去webpack官网阅读输出选项
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多