打字稿和webpack

时间:2015-11-05 12:41:50

标签: javascript typescript webpack commonjs

我对webpack和打字稿有些困难。我的项目中的不同文件夹中有许多.ts文件。之前我没有使用像commonjs或AMD这样的模块系统,但使用了typescript命名空间(模块关键字)。这些文件没有连接成单个文件。这意味着生成了附近的每个.ts文件.js文件,然后所有的.js文件都包含在HTML中。

现在我尝试使用webpack和ts-loader。

module.exports = {
    context: __dirname,
    entry: "app.ts",
    output: {
        path: __dirname,
        filename: 'bundle.js'
    },
    resolve: {
         root: __dirname,
         extensions: ["", ".webpack.js", ".web.js", ".js",".ts", ".tsx"]
    },
    module: {
        loaders: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader'
            }
        ]
    }
}

在bundle.js文件中编译后,我只能找到app.ts编译的内容,但不能找到所有其他文件。据我所知,这是因为我没有使用import关键字。 Webpack ts-loader只编译那些模块的文件。如果我启动typescript编译器,它将编译我项目中的所有文件。

问题是:如何在bundle.js中添加所有的typescript文件,即使它们不是commonjs模块? 感谢。

2 个答案:

答案 0 :(得分:1)

不确定您是否能够获得不使用CJS或UMD的模块,但也许我不理解这个问题?如果您只想连接和捆绑ts,tsx文件而不管导入和扩展,您可以将ExtractTextPlugin与相应的加载器一起使用。这样的事情可能有用。

module: {
    loaders: [
        {
            test: /\.tsx?$/,
            loader: ExtractTextPlugin.extract('ts-loader')
        }
    ]
},
plugins: [
    new ExtractTextPlugin('typescript.[chunkhash].js', {
        disable: false,
        allChunks: true // extract all ts
    }),

这是documentation

答案 1 :(得分:0)

我猜你实际上并不需要webpack。您只需使用"文件"定义tsconfig.json即可。财产,那么" tsc"应该做你需要的所有工作。

{
  "compilerOptions": {
    "target": "es6",
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "allowJs": true,
    "outDir": "build"
  },
  "exclude": ["node_modules"],
  "files": ["typings/index.d.ts", "entry.ts", "file1.ts", "file2.ts" , .... ]
}

您还可以配置" compilerOptions.module" to" amd"," none"," umd"," commonjs" ...设置模块加载。