简体   繁体   中英

Typescript and webpack

I have some difficulties with webpack and typescript. There are many .ts files in different folders in my project. Earlier I didn't use module system like commonjs or AMD but typescript namespaces (module keyword) were used. The files were not concatenated into single one. It means that nearby each .ts file .js file were generated and then all the .js files were included in HTML.

Now I try to use webpack and 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'
            }
        ]
    }
}

After compile in the bundle.js file I can find only the app.ts compiled content, but not all the other files. As I understood it is because I didn't use the import keyword. Webpack ts-loader compile only those files that are modules. If I start typescript compiler it will compile all the files in my project as earlier.

The question is: how to add in bundle.js all the typescript files even if they are not ie commonjs modules? Thanks.

Not sure you will be able to get the modules that don't use CJS, or UMD, but perhaps I'm not understanding the problem? If you just want to concatenate and bundle your ts, tsx files regardless of imports and based on extension, you can use the ExtractTextPlugin with the corresponding loader. Something like this might work.

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

Here's the documentation .

I guess you don't actually need webpack. You can simply define your tsconfig.json with the "files" property, then "tsc" should do all the work you need.

{
  "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" , .... ]
}

You can also configure the "compilerOptions.module" to "amd", "none", "umd", "commonjs" ... to setup the module loading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM