Webpack dev server typescript

Configuration Languages

Webpack accepts configuration files written in multiple programming and data languages. The list of supported file extensions can be found in the node-interpret package. Using node-interpret, webpack can handle many different types of configuration files.

TypeScript

To write the webpack configuration in TypeScript, you would first install the necessary dependencies, i.e., TypeScript and the relevant type definitions from the DefinitelyTyped project:

npm install --save-dev typescript ts-node @types/node @types/webpack # and, if using webpack-dev-server < v4.7.0npm install --save-dev @types/webpack-dev-server

and then proceed to write your configuration:

webpack.config.ts

import path from 'path'; import webpack from 'webpack'; // in case you run into any typescript error when configuring `devServer` import 'webpack-dev-server'; const config: webpack.Configuration =  mode: 'production', entry: './foo.js', output:  path: path.resolve(__dirname, 'dist'), filename: 'foo.bundle.js', >, >; export default config;

tsconfig.json

 "compilerOptions":  "allowSyntheticDefaultImports": true, "esModuleInterop": true > >

The above sample assumes version >= 2.7 or newer of TypeScript is used with the new esModuleInterop and allowSyntheticDefaultImports compiler options in your tsconfig.json file.

Note that you’ll also need to check your tsconfig.json file. If the module in compilerOptions in tsconfig.json is commonjs , the setting is complete, else webpack will fail with an error. This occurs because ts-node does not support any module syntax other than commonjs .

There are three solutions to this issue:

  • Modify tsconfig.json .
  • Modify tsconfig.json and add settings for ts-node .
  • Install tsconfig-paths .

The first option is to open your tsconfig.json file and look for compilerOptions . Set target to «ES5» and module to «CommonJS» (or completely remove the module option).

The second option is to add settings for ts-node:

You can keep «module»: «ESNext» for tsc , and if you use webpack, or another build tool, set an override for ts-node. ts-node config

 "compilerOptions":  "module": "ESNext", >, "ts-node":  "compilerOptions":  "module": "CommonJS" > > >

The third option is to install the tsconfig-paths package:

npm install --save-dev tsconfig-paths

And create a separate TypeScript configuration specifically for your webpack configs:

tsconfig-for-webpack-config.json

 "compilerOptions":  "module": "commonjs", "target": "es5", "esModuleInterop": true > >
tip

ts-node can resolve a tsconfig.json file using the environment variable provided by tsconfig-paths .

Then set the environment variable process.env.TS_NODE_PROJECT provided by tsconfig-paths like so:

package.json

 "scripts":  "build": "cross-env TS_NODE_PROJECT=\"tsconfig-for-webpack-config.json\" webpack" > >
warning

We had been getting reports that TS_NODE_PROJECT might not work with «TS_NODE_PROJECT» unrecognized command error. Therefore running it with cross-env seems to fix the issue, for more info see this issue.

CoffeeScript

Similarly, to use CoffeeScript, you would first install the necessary dependencies:

npm install --save-dev coffeescript

and then proceed to write your configuration:

webpack.config.coffee

HtmlWebpackPlugin = require('html-webpack-plugin') webpack = require('webpack') path = require('path') config = mode: 'production' entry: './path/to/my/entry/file.js' output: path: path.resolve(__dirname, 'dist') filename: 'my-first-webpack.bundle.js' module: rules: [ < test: /\.(js|jsx)$/ use: 'babel-loader' >] plugins: [ new HtmlWebpackPlugin(template: './src/index.html') ] module.exports = config 

Babel and JSX

In the example below JSX (React JavaScript Markup) and Babel are used, to create a JSON configuration that webpack can understand.

First, install the necessary dependencies:

npm install --save-dev babel-register jsxobj babel-preset-es2015

webpack.config.babel.js

import jsxobj from 'jsxobj'; // example of an imported plugin const CustomPlugin = (config) => ( . config, name: 'custom-plugin', >); export default ( webpack target="web" watch mode="production"> entry path="src/index.js" /> resolve> alias .  react: 'preact-compat', 'react-dom': 'preact-compat', >> /> /resolve> plugins> CustomPlugin foo="bar" /> /plugins> /webpack> );
warning

If you are using Babel elsewhere and have modules set to false , you will have to either maintain two separate .babelrc files or use const jsxobj = require(‘jsxobj’); and module.exports instead of the new import and export syntax. This is because while Node does support many new ES6 features, they don’t yet support ES6 module syntax.

Источник

TypeScript

This guide stems from the Getting Started guide.

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. In this guide we will learn how to integrate TypeScript with webpack.

Basic Setup

First install the TypeScript compiler and loader by running:

npm install --save-dev typescript ts-loader

Now we’ll modify the directory structure & the configuration files:

  webpack-demo |- package.json |- package-lock.json + |- tsconfig.json   |- webpack.config.js |- /dist |- bundle.js |- index.html |- /src |- index.js + |- index.ts   |- /node_modules

tsconfig.json

Let’s set up a configuration to support JSX and compile TypeScript down to ES5.

 "compilerOptions":  "outDir": "./dist/", "noImplicitAny": true, "module": "es6", "target": "es5", "jsx": "react", "allowJs": true, "moduleResolution": "node" > >

See TypeScript’s documentation to learn more about tsconfig.json configuration options.

To learn more about webpack configuration, see the configuration concepts.

Now let’s configure webpack to handle TypeScript:

webpack.config.js

const path = require('path'); module.exports =  entry: './src/index.ts', module:  rules: [  test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, >, ], >, resolve:  extensions: ['.tsx', '.ts', '.js'], >, output:  filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), >, >;

This will direct webpack to enter through ./index.ts , load all .ts and .tsx files through the ts-loader , and output a bundle.js file in our current directory.

Now lets change the import of lodash in our ./index.ts due to the fact that there is no default export present in lodash definitions.

- import _ from 'lodash'; + import * as _ from 'lodash';   function component()  const element = document.createElement('div');   element.innerHTML = _.join(['Hello', 'webpack'], ' ');   return element; >   document.body.appendChild(component());
tip

To make imports do this by default and keep import _ from ‘lodash’; syntax in TypeScript, set «allowSyntheticDefaultImports» : true and «esModuleInterop» : true in your tsconfig.json file. This is related to TypeScript configuration and mentioned in our guide only for your information.

Loader

We use ts-loader in this guide as it makes enabling additional webpack features, such as importing other web assets, a bit easier.

warning

ts-loader uses tsc , the TypeScript compiler, and relies on your tsconfig.json configuration. Make sure to avoid setting module to «CommonJS», or webpack won’t be able to tree-shake your code.

Note that if you’re already using babel-loader to transpile your code, you can use @babel/preset-typescript and let Babel handle both your JavaScript and TypeScript files instead of using an additional loader. Keep in mind that, contrary to ts-loader , the underlying @babel/plugin-transform-typescript plugin does not perform any type checking.

Source Maps

To learn more about source maps, see the development guide.

To enable source maps, we must configure TypeScript to output inline source maps to our compiled JavaScript files. The following line must be added to our TypeScript configuration:

tsconfig.json

    "compilerOptions":  "outDir": "./dist/", + "sourceMap": true,   "noImplicitAny": true, "module": "commonjs", "target": "es5", "jsx": "react", "allowJs": true, "moduleResolution": "node", > >

Now we need to tell webpack to extract these source maps and include in our final bundle:

webpack.config.js

  const path = require('path');   module.exports =  entry: './src/index.ts', + devtool: 'inline-source-map',   module:  rules: [   test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, >, ], >, resolve:  extensions: [ '.tsx', '.ts', '.js' ], >, output:  filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), >, >;

See the devtool documentation for more information.

Client types

It’s possible to use webpack specific features in your TypeScript code, such as import.meta.webpack . And webpack provides types for them as well, just add a TypeScript reference directive to declare it:

///  console.log(import.meta.webpack); // without reference declared above, TypeScript will throw an error

Using Third Party Libraries

When installing third party libraries from npm, it is important to remember to install the typing definition for that library. These definitions can be found at TypeSearch.

For example if we want to install lodash we can run the following command to get the typings for it:

npm install --save-dev @types/lodash

Importing Other Assets

To use non-code assets with TypeScript, we need to defer the type for these imports. This requires a custom.d.ts file which signifies custom definitions for TypeScript in our project. Let’s set up a declaration for .svg files:

declare module '*.svg'  const content: any; export default content; >

Here we declare a new module for SVGs by specifying any import that ends in .svg and defining the module’s content as any . We could be more explicit about it being a url by defining the type as string. The same concept applies to other assets including CSS, SCSS, JSON and more.

Build Performance

warning

This may degrade build performance.

See the Build Performance guide on build tooling.

Источник

Читайте также:  Javascript splice or delete
Оцените статью