hgiesel
hgiesel

Reputation: 5648

How to make webpack consume files

So I use Typescript with Webpack.

tsc compiles everything from .ts to .js and then I want to use webpack to make it usable by the browser. However the problem is that I still have all of these .js files lying around from tsc. Is there some way to tell webpack:

"Pack all these things into a nice bundle, and destroy them after you're done!"

Upvotes: 0

Views: 117

Answers (2)

dominik791
dominik791

Reputation: 752

Yes, it's possible. I recommend using awesome-typescript-loader for this purpose.

const rootDir = path.resolve(__dirname);
const path = require('path');

module.exports = {
  entry: {
    boot: [path.resolve(rootDir, 'src', 'boot')]
  },
  output: {
    filename: 'js/[name].bundle.js',
    path: path.resolve(rootDir, 'build')
  },
  module: {
    loaders: [
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js']
  }
};

If you use 3rd party modules or libraries, it's also recommended to create separate bundle for vendor files and use webpack.optimize.CommonsChunkPlugin. Check out configuration of webpack-typescript-postcss-universal-starter to see how you can easily use it.

Upvotes: 1

Paarth
Paarth

Reputation: 10377

Yes, use the typescript loader for webpack.

The Configuration section of that page presents a sample webpack config

module.exports = {
  entry: './app.ts',
  output: {
    filename: 'bundle.js'
  },
  resolve: {
    // Add `.ts` and `.tsx` as a resolvable extension.
    extensions: ['.ts', '.tsx', '.js'] // note if using webpack 1 you'd also need a '' in the array as well
  },
  module: {
    loaders: [ // loaders will work with webpack 1 or 2; but will be renamed "rules" in future
      // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
      { test: /\.tsx?$/, loader: 'ts-loader' }
    ]
  }
}

As a second real world example, here is the appropriate section from my personal webpack.config.js which also sets up babel and (p)react

module: {
    rules: [
        {
            test: /\.ts(x?)$/,
            exclude: /node_modules/,
            use: [
                {
                    loader: 'babel-loader',
                    query: {
                        presets: ['es2015']
                    }
                },
                'ts-loader'
            ]
        }
    ]
},
resolve: {
    modules: [
        __dirname,
        'node_modules'
    ],
    extensions: ['.ts','.tsx','.js'],
    alias: {
        'react': 'preact-compat/dist/preact-compat.js',
        'react-dom': 'preact-compat/dist/preact-compat.js'
    }
},

Upvotes: 3

Related Questions