Webpack2 + Typescript2 fails to dynamic import json - javascript

I have a problem at import json dynamically using webpack.
(https://webpack.js.org/api/module-methods/#import-)
It keep shows this error - TS2307: Cannot find module
package versions are..
webpack version: 2.7.0
typescript version: 2.4.2
awesome-typescript-loader: 3.2.1
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "esnext",
"moduleResolution": "node",
"target": "es6",
"jsx": "react",
"allowJs": true,
"allowSyntheticDefaultImports": true
},
"awesomeTypescriptLoaderOptions": {
"useBabel": true,
"useCache": true
},
"exclude": ["node_modules"],
"include": [
"./components/**/*",
"./core/*",
"./pages/*",
"./utils/*",
"./urls/*",
"./translations/**/*",
"./main.tsx"
]
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const AssetsPlugin = require('assets-webpack-plugin');
const pkg = require('./package.json');
const isDebug = global.DEBUG === false ? false : !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose') || process.argv.includes('-v');
const useHMR = !!global.HMR; // Hot Module Replacement (HMR)
const babelConfig = Object.assign({}, pkg.babel, {
babelrc: false,
cacheDirectory: useHMR,
});
// Webpack configuration (main.js => public/dist/main.{hash}.js)
// http://webpack.github.io/docs/configuration.html
const config = {
// The base directory for resolving the entry option
context: __dirname,
// The entry point for the bundle
entry: [
// require('babel-polyfill'),
'./main.tsx'
],
// Options affecting the output of the compilation
output: {
path: path.resolve(__dirname, './public/dist'),
publicPath: '/dist/',
filename: isDebug ? '[name].js?[hash]' : '[name].[hash].js',
chunkFilename: isDebug ? '[id].js?[chunkhash]' : '[id].[chunkhash].js',
sourcePrefix: ' ',
},
// Developer tool to enhance debugging, source maps
// http://webpack.github.io/docs/configuration.html#devtool
devtool: isDebug ? 'inline-source-map' : false,
// What information should be printed to the console
stats: {
colors: true,
reasons: isDebug,
hash: isVerbose,
version: isVerbose,
timings: true,
chunks: isVerbose,
chunkModules: isVerbose,
cached: isVerbose,
cachedAssets: isVerbose,
},
// The list of plugins for Webpack compiler
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
__DEV__: isDebug,
}),
// Emit a JSON file with assets paths
// https://github.com/sporto/assets-webpack-plugin#options
new AssetsPlugin({
path: path.resolve(__dirname, './public/dist'),
filename: 'assets.json',
prettyPrint: true,
}),
],
// Options affecting the normal modules
module: {
rules: [
{
test: /\.tsx?$/,
include: [
path.resolve(__dirname, './components'),
path.resolve(__dirname, './core'),
path.resolve(__dirname, './pages'),
path.resolve(__dirname, './apis'),
path.resolve(__dirname, './urls'),
path.resolve(__dirname, './translations'),
path.resolve(__dirname, './main')
],
loader: 'awesome-typescript-loader'
},
{
test: /\.css/,
use: [{loader: 'style-loader'}, {loader: 'css-loader', options:
{
sourceMap: isDebug,
// CSS Modules https://github.com/css-modules/css-modules
modules: true,
localIdentName: isDebug ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]',
// CSS Nano http://cssnano.co/options/
minimize: !isDebug,
}},
// {loader: 'postcss-loader'}
],
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader?limit=10000',
},
{
test: /\.(eot|ttf|wav|mp3)$/,
loader: 'file-loader',
},
],
},
externals: {
react: 'React'
},
resolve: {
extensions: ['.js', '.ts', '.tsx']
}
};
// Optimize the bundle in release (production) mode
if (!isDebug) {
config.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: isVerbose }, sourceMap: isDebug }));
config.plugins.push(new webpack.optimize.AggressiveMergingPlugin());
}
// Hot Module Replacement (HMR) + React Hot Reload
if (isDebug && useHMR) {
babelConfig.plugins.unshift('react-hot-loader/babel');
config.entry.unshift('react-hot-loader/patch', 'webpack-hot-middleware/client');
config.plugins.push(new webpack.HotModuleReplacementPlugin());
config.plugins.push(new webpack.NoEmitOnErrorsPlugin());
}
module.exports = config;
custom.d.ts
declare module "*.json" {
const value: any;
export default value;
}
my error code
// TS2307: Cannot find module './test.json'.
import('./test.json').then(_ => {
console.log(_
})
// but these codes work
import './test.json'
import('./test.js').then(_ => { console.log(_)})
I have searched issues as much as possible I can. but no one seems to encountered this issue.
Here's related links what I found.
https://github.com/Microsoft/TypeScript/issues/16820
https://blog.josequinto.com/2017/06/29/dynamic-import-expressions-and-webpack-code-splitting-integration-with-typescript-2-4/
If anyone have a clue, please let me know.

Are you sure your custom.d.ts is in a folder included in the compilation? I believe only typings in packages under node_modules/#types are included if they are not in the "files" or "include" properties in tsconfig.json.

Related

"Parsing error: invalid character" when bundling images with Webpack's loaders

When I'm trying to bundle my React project, I get the following error regarding an image I'm about to load:
Oddly enough, when I hide the error overlay, I can see in a browser that my picture has been loaded correctly, despite Webpack's complaints. I've already been carefully following other working config examples, where that problem doesn't occur, but I can't easily identify the source of the issue, what leaves me here with no idea how to approach it or where to look for a hint. I've also tried different loaders: url-loader, file-loader and image-webpack-loader, but to no avail. Maybe that's Typescript what causes these troubles?
App.tsx where I'm importing my image:
import "./app.d";
import React from "react";
import SampleImage from "./assets/images/sample-image.jpg";
const App: React.FC = () => (
<div>
<img src={SampleImage} />
</div>
);
export default App;
app.d.ts with modules declarations to allow importing assets in typescripts files:
declare module "*.jpeg";
declare module "*.jpg";
declare module "*.jpeg";
declare module "*.png";
webpack.common.ts - my main Webpack config file, where I placed both url-loader and file-loader as it is in ejected create-react-app config, but it doesn't really change anything:
import path from "path";
import ForkTsCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin";
import HtmlWebpackPlugin from "html-webpack-plugin";
import { CleanWebpackPlugin } from "clean-webpack-plugin";
module.exports = {
entry: path.resolve(__dirname, "..", "./src/index.tsx"),
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: require.resolve("babel-loader"),
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript",
],
},
},
],
},
{
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.(ts|tsx)$/,
/\.css$/,
/\.json$/,
/\.bmp$/,
/\.gif$/,
/\.jpe?g$/,
/\.png$/,
],
loader: require.resolve("file-loader"),
options: {
name: "static/media/[name].[hash:8].[ext]",
},
include: path.resolve(__dirname, "..", "./src/assets"),
},
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve("url-loader"),
options: {
name: "static/media/[name].[hash:8].[ext]",
},
include: path.resolve(__dirname, "..", "./src/assets"),
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js", ".jsx"],
},
output: {
path: path.resolve(__dirname, "..", "./dist"),
filename: "bundle.js",
},
devServer: {
contentBase: path.resolve(__dirname, "..", "./dist"),
hot: true,
compress: true,
open: true,
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "React App",
template: path.resolve(__dirname, "..", "./src/index.html"),
}),
new ForkTsCheckerWebpackPlugin({
async: false,
eslint: {
files: path.resolve(__dirname, "..", "./src/**/*"),
},
}),
],
};
webpack.dev.ts
import webpack from "webpack";
import ReactRefreshWebpackPlugin from "#pmmmwh/react-refresh-webpack-plugin";
module.exports = {
mode: "development",
devtool: "eval-source-map",
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: require.resolve("babel-loader"),
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript",
],
plugins: [require.resolve("react-refresh/babel")],
},
},
],
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new ReactRefreshWebpackPlugin({
overlay: {
sockIntegration: "wds",
},
}),
],
};
webpack.prod.ts
import webpack from "webpack";
module.exports = {
mode: "production",
devtool: "source-map",
};
webpack.config.ts
import merge from "webpack-merge";
import devConfig = require("./webpack.dev");
import prodConfig = require("./webpack.prod");
import commonConfig = require("./webpack.common");
module.exports = ({ env }: { env: "dev" | "prod" }) => {
const envConfig = env === "dev" ? devConfig : prodConfig;
return merge(commonConfig, envConfig);
};
Additionaly, my .babelrc file:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript"
],
"plugins": [
"react-refresh/babel",
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
and tsconfig.json:
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"esModuleInterop": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": ["src"]
}
Scripts in package.json:
"scripts": {
"start": "webpack serve --config config/webpack.config.ts --env env=dev --hot",
"build": "webpack --config config/webpack.config.ts --env env=prod",
},
I'd be really grateful for any hint how to solve the issue.
Thanks to help received here: https://github.com/webpack/webpack/issues/12276#event-4152056913, I've managed to surpass the error overlay by changing the options passed to the ForkTsCheckerWebpackPlugin in my webpack.common.ts file.
Before:
new ForkTsCheckerWebpackPlugin({
async: false,
eslint: {
files: path.resolve(__dirname, "..", "./src/**/*"),
},
}),
Now:
new ForkTsCheckerWebpackPlugin({
async: false,
eslint: {
files: path.resolve(__dirname, "..", "./src/**/*.{ts,tsx,js,jsx}"),
},
}),

Hot reload with typescript and webpack

I'm facing problems while developing both frontend (Redux) and backend (Express) in Typescript. I could not make hot reload work. Here is configuration of webpack.config.js in root folder:
const webpack = require('webpack');
const path = require('path');
const { CheckerPlugin } = require('awesome-typescript-loader');
const config = {
cache: true,
mode: 'development',
entry: {
'user': ['./dist/client/User/index', 'webpack-hot-middleware/client'],
'guest': ['./dist/client/Guest/index', 'webpack-hot-middleware/client']
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CheckerPlugin()
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/static'
},
devServer: {
contentBase: './dist',
hot: true
},
resolve: {
extensions: ['.tsx', '.ts', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'awesome-typescript-loader',
exclude: /node_modules/,
include: path.join(__dirname, 'client'),
options: { cacheDirectory: true }
}
]
},
node: { fs: 'empty' }
};
module.exports = config;
And tsconfig.json:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"jsx": "react",
"esModuleInterop": true,
"outDir": "dist",
"sourceMap": true,
"baseUrl": "."
},
"include": ["src/**/*.ts", "src/**/*.tsx"],
"exclude": ["node_modules"]
}
In src I separate two folders client and server, my npm start script is tsc && node dist/server. In server/index I declare utilization of webpack compiler like this:
import config from '../../webpack.config';
const compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
When I start the application, webpack builds normally, but it never build hot reload when I make changes in client files. I spent a whole day but still confused and don't know how to fix it yet.
are you currently using react 17?
if so, create the following in the .env file
FAST_REFRESH=false
directory

Cannot access prototype after compiling with Webpack in Typescritp

I Converted an old Javascript library for the company I work with, to a brand new Typescript Library. I use WebPack since I heard i need a module management system in order to make my library works in the browser. Problem is, whenever i'm trying to initiate my library ( in the JQuery function $(document).ready() , i cannot access my object prototype, I got a typeError :
Uncaught TypeError: Cannot read property 'loadPage' of undefined
Here is my code :
webpack.config.js
const path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var UglifyJsPlugin = require('uglifyjs-webpack-plugin');
var webpack = require("webpack");
var fs = require("fs");
module.exports = {
entry: './src/libraryLoader.ts',
module: {
rules: [
{
test: /\.(tsx?)$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.json$/,
use: {
loader: "file-loader",
options: {
name: "[name].[ext]",
publicPath: "config/"
}
},
exclude: /node_modules/
}
]
},
plugins: [
new CopyWebpackPlugin([
{ from: 'src/settings/config', to: "config" }
]),
new UglifyJsPlugin({
uglifyOptions: {
ie8: true,
//compress: true
}
}),
new webpack.BannerPlugin({
banner: fs.readFileSync('./copyright', 'utf8'),
raw: true
})
],
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
modules: [
"node_modules"
]
},
// Enable sourcemaps for debugging webpack's output.
devtool: "eval",
output: {
filename: 'library.min.js',
path: path.resolve(__dirname, 'dist'),
},
watch: false,
watchOptions: {
ignored: /node_modules/
},
externals: {
// require("jquery") is external and available
// on the global var jQuery
"jquery": "jQuery"
}
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"moduleResolution": "node",
"module": "commonjs",
"outDir": "build",
"strict": true,
"noImplicitAny": true,
"allowJs": true,
"sourceMap": true,
"typeRoots": [
"./node_modules/#types"
],
"project": "src",
"lib": [ "es2015", "dom"]
},
"include": [
"src/**/*",
"typings/**/*"
]
}
Where I load my library :
$(document).ready(function () {
let loader = new LibraryLoader();
loader.library().loadPage(); // <- Error here
/*...*/
});
My Loader class
export class LibraryLoader{
private _library: Library;
public LibraryLoader() {
this.setLibrary(new Library(/* ... unrelated options ... */));
}
public library(): Library{
return this._library;
}
private setLibrary(value: Library) : void {
this._library = value;
}
}
P.S. There is a loadPage function in the library, but the function library() return undefined anyways,

WebPack optimization with Awesome-Typescript-Loader not seeing much improvement

I'm trying to improve my WebPack performance so I switched out TS-Loader for Awesome-TypeScript-Loader, and my compile times only increased a tiny bit. I had heard ATL is supposed to be much faster, but I only shaved off maybe a few 100ms.
Here's my webpack.config.js:
'use strict';
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
const CleanWebpackPlugin = require('clean-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const WebpackNotifierPlugin = require('webpack-notifier');
const { CheckerPlugin, TsConfigPathsPlugin } = require('awesome-typescript-loader')
// const ExtractTextPlugin = require('extract-text-webpack-plugin')
// borrowed from the ng2 seed
const entryPoints = ['inline', 'polyfills', 'sw-register', 'styles', 'vendor', 'app'];
const htmlConfig = {
template: 'client/_index.html',
filename: 'index.html',
// borrowed from the ng2 seed
chunksSortMode: (left, right) => {
const leftIndex = entryPoints.indexOf(left.names[0]);
const rightIndex = entryPoints.indexOf(right.names[0]);
if (leftIndex > rightIndex) {
return 1;
} else if (leftIndex < rightIndex) {
return -1;
} else {
return 0;
}
}
};
function isExternal(module) {
const match = typeof module.userRequest === 'string' &&
/node_modules/.test(module.userRequest.split('!').pop());
return match;
}
// const extractCSS = new ExtractTextPlugin({ filename: '[name].[hash].css', allChunks: true })
// const extractJS = new ExtractTextPlugin({ filename: '[name].[hash].js', allChunks: true })
module.exports = {
cache: true,
entry: {
polyfills: './client/app/polyfills.js',
// base: './client/base.js',
app: './client/app/app.ts'
},
output: {
// Absolute output directory
path: path.join(__dirname, '/dist/'),
// Output path from the view of the page
// Uses webpack-dev-server in development
publicPath: '/',
// Filename for entry points
// Only adds hash in build mode
filename: '[name].[hash].js',
// Filename for non-entry points
// Only adds hash in build mode
chunkFilename: '[name].[hash].js'
},
resolve: {
modules: [
path.resolve(__dirname, 'client'),
'node_modules'
],
extensions: ['.ts', '.js'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'vue-router$': 'vue-router/dist/vue-router.esm.js',
'vuex$': 'vuex/dist/vuex.esm.js',
'vuex-class$': 'vuex-class/dist/vuex-class.cjs.js',
'styles': path.resolve(__dirname, 'client/app/styles'),
'core': path.resolve(__dirname, 'client/app/core'),
'components': path.resolve(__dirname, 'client/app/components'),
'containers': path.resolve(__dirname, 'client/app/containers'),
'assets': path.resolve(__dirname, 'client/assets'),
'config': path.resolve(__dirname, 'client/config')
}
},
// Use 'source-map' for more accurate source mapping
// Use 'cheap-module-eval-source-map' for faster rebuilding
devtool: 'cheap-module-eval-source-map',
module: {
rules: [
{
// ES LINT LOADER
// Reference: https://github.com/MoOx/eslint-loader
// Lint ECMAScript
enforce: 'pre',
test: /\.js$/,
use: [
{ loader: 'eslint-loader', options: { cache: true } }
],
include: [path.resolve(__dirname, 'client')]
},
{
// TS LINT LOADER
// Reference: https://github.com/wbuchwalter/tslint-loader
// Lint TypeScript
enforce: 'pre',
test: /\.ts$/,
use: ['tslint-loader'],
include: [path.resolve(__dirname, 'client')]
},
{
// SOURCE MAP LOADER
// Reference: https://github.com/webpack-contrib/source-map-loader
// Extracts SourceMaps for source files that as added as sourceMappingURL comment
enforce: 'pre',
test: /\.(j|t|s?(a|c)s)s$/, // ts or js or css or scss or sass (or ass)
use: ['source-map-loader'],
exclude: [path.resolve(__dirname, 'node_modules/css-loader/lib/convert-source-map.js')] // There is a sourceMappingURL example in this file that triggers a warning
},
{
// JS LOADER
// Reference: https://github.com/babel/babel-loader
// Transpile .js files using babel-loader
// Compiles ES6 and ES7 into ES5 code
test: /\.js$/,
use: [
{ loader: 'babel-loader', options: { sourceMap: true, cacheDirectory: true } }
],
exclude: [path.resolve(__dirname, 'node_modules')]
},
{
// AWESOME TYPESCRIPT LOADER
// Reference: https://github.com/s-panferov/awesome-typescript-loader
// Transpile .ts files using awesome-typescript-loader
// Compiles TS into ES6 code
test: /\.ts$/,
use: [
// { loader: 'babel-loader', options: { sourceMap: true, cacheDirectory: true } },
// { loader: 'ts-loader' }
{ loader: 'awesome-typescript-loader', options: { sourceMap: true, useCache: true, useBabel: true, useTranspileModule: true } }
],
exclude: [path.resolve(__dirname, 'node_modules')]
},
{
// ASSET LOADER
// Reference: https://github.com/webpack/url-loader
// Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
// Rename the file using the asset hash
// Pass along the updated reference to your code
// You can add here any file extension you want to get copied to your output
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot|mp4)([?]?.*)$/,
use: [
{ loader: 'file-loader', options: { name: 'assets/[name].[hash].[ext]' } }
]
},
{
// HTML LOADER
// Reference: https://github.com/webpack/html-loader
// Allow loading html through js
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: {
sourceMap: true,
exportAsEs6Default: true,
root: path.resolve(__dirname, 'client'),
// Look for and process the following tag:attr on html elements
attrs: [
'img:src',
'video:src'
]
}
}
]
},
{
// CSS LOADER
// Reference: https://github.com/webpack-contrib/css-loader
test: /\.css$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { sourceMap: true, importLoaders: 1 } },
{ loader: 'postcss-loader', options: { sourceMap: true } }
]
},
{
// SASS LOADER
// Reference: https://github.com/jtangelder/sass-loader
test: /\.s(a|c)ss$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { sourceMap: true, importLoaders: 2 } },
{ loader: 'postcss-loader', options: { sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true } }
]
}
]
},
plugins: [
new webpack.LoaderOptionsPlugin({
cache: true,
debug: true,
minimize: false
}),
new webpack.NamedModulesPlugin(),
new WebpackNotifierPlugin(),
new TsConfigPathsPlugin(),
new CheckerPlugin(),
new StyleLintPlugin({
files: ['./client/**/*.s?(a|c)ss']
}),
// Remove dist and build directories before building
new CleanWebpackPlugin(['dist']),
// extractCSS,
new CommonsChunkPlugin({
name: 'vendor',
// Only analyze the app entry point, we don't want to change the others
chunks: ['app'],
// Check if module is in node_modules
minChunks: (module) => {
return isExternal(module);
}
}),
new HtmlWebpackPlugin(htmlConfig)
],
devServer: {
historyApiFallback: true,
compress: false,
inline: true,
hot: true
}
};
And my tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"target": "ES2017",
"module": "ES2015",
"moduleResolution": "Node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"allowSyntheticDefaultImports": true,
"noEmitHelpers": true,
"importHelpers": true,
"pretty": true,
"alwaysStrict": true,
"lib": [
"DOM",
"ES2017",
"DOM.Iterable",
"ScriptHost"
],
"baseUrl": ".",
"paths": {
"styles/*": ["./client/app/styles/*"],
"core/*": ["./client/app/core/*"],
"components/*": ["./client/app/components/*"],
"containers/*": ["./client/app/containers/*"],
"assets/*": ["./client/assets/*"],
"config/*": ["./client/config/*"]
}
}
}
And the .babelrc file:
{
"presets": [
[
"env", {
"modules": false,
"useBuiltIns": true,
"debug": true,
"targets": {
"browsers": [
"last 1 Chrome version"
]
}
}]
]
}
I'm targeting ES2017 from TS and leaving it up to Babel to compile for our target browser; as in development we want the extra performance of native code, and less difference of the transpiled coutput.
It seems to be hung up on Babel, especially, as it gets bogged down in the "asset optimization" stage.
TS-loader + Babel: ~1500ms
ATL + Babel: ~1100ms
ATL - Babel: ~800ms
Also, I don't see any performance difference with ATL between useCache: true/false nor useTranspileModule: true/false. But I do see it making a TON of files in the .awcache folder, every time it recompiles (wondering if something is cache busting).
Running webpack-dev-server with params:
webpack-dev-server --watch --hot --progress --open
Using the latest versions of all packages, loaders, and tools as of this post.
Any help would be greatly appreciated!
Thanks!

Strange compiled JS file from TypeScript & web pack

I'm migrating my plugin from gulp to webpack 2 and I have an issue with the completed js file.
the file is minified & compressed.
My web pack config file :
// webpack.config.js
const webpack = require('webpack');
const config = {
entry: './src/ts/amt-rating.ts',
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
loader: 'ts-loader?tsconfig=tsconfig.json'
}
]
},
plugins:[
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}
})
]
}
//if production
if (process.env.NODE_ENV === 'production') {
config.output = {
filename: 'dist/js/amt-rating.min.js'
}
//uglify js options
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
minimize: true
}
})
)
}
else{
config.output = {
filename: 'dist/js/amt-rating.js'
}
config.devtool = "#cheap-module-source-map"
}
module.exports = config;
And here my tsconfig file :
{
"compilerOptions": {
"target": "es5",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
},
"include": [
"src/ts/*.ts"
],
"exclude": [
"node_modules"
]
}
I wan't to compile my typescript into a very simple javascript file without any dependencies.
This enables minification and compression:
//uglify js options
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
minimize: true
}
})
)
and is set to run if NODE_ENV is set to production. Make sure you have set it to development to get the not minified version.

Categories

Resources