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

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!

Related

Read the contents of the module file/stream into a BLOB

I create a BLOB file and write JavaScipt code there, then create a URL and import the module from it.
const myJSFile = new Blob( [ 'export default true;' ], { type: 'application/javascript' } );
const myJSURL = URL.createObjectURL( myJSFile );
import( myJSURL ).then(async ( module ) => {
console.log( module.default );
});
This works great in the browser console. However, I am having a problem when building a project using Webpack.
I suspect the problem is with WebPack or Babel configuration.
Webpack common config:
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
// Where webpack looks to start building the bundle
entry: [
'core-js/modules/es6.promise',
'core-js/modules/es6.array.iterator',
'./src/main.js',
],
target: 'web',
// Where webpack outputs the assets and bundles
output: {
path: path.resolve(__dirname, 'dist'),
assetModuleFilename: '[name].[contenthash].[ext]',
filename: '[name].[contenthash].bundle.js',
chunkFilename: '[id].[chunkhash].bundle.js',
// publicPath: '/',
},
// Determine how modules within the project are treated
module: {
rules: [
{
test: /\.(gif|png|jpe?g)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/images/'
}
}
]
},
// JavaScript: Use Babel to transpile JavaScript files
{ test: /\.js$/, use: ['babel-loader'] },
// Images: Copy image files to build folder
{ test: /\.(?:ico|gif|png|jpg|jpeg)$/i, type: 'asset/resource' },
// Fonts and SVGs: Inline files
{ test: /\.(woff(2)?|eot|ttf|otf|svg|)$/, type: 'asset/inline' },
],
},
// Customize the webpack build process
plugins: [
// Generates an HTML file from a template
new HtmlWebpackPlugin({
// template: path.resolve(__dirname, 'src/index.html'), // шаблон
template: 'src/index.html',
// filename: 'index.html', // название выходного файла
// inject: false, // true, 'head'
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
},
// chunks: 'all',
// excludeChunks: [],
}),
new CopyWebpackPlugin(
{
patterns: [
{ from: 'src/assets', to: 'assets' },
// { from: 'src/components', to: 'components' },
]
}
),
],
resolve: {
// modules: [path.resolve(__dirname, 'src'), 'node_modules'],
extensions: ['.js', '.jsx', '.json', '.ts'],
alias: {
'#': [
path.resolve(__dirname, 'src'),
'./src/main.js'
],
},
},
}
Babel config
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
esmodules: true,
},
},
],
],
plugins: [
'#babel/plugin-proposal-class-properties',
'#babel/plugin-transform-runtime',
"#babel/plugin-syntax-dynamic-import"
]
};
I've used require-from-string before, which internally uses the native Module module to achieve this.
Speaking generally, Blobs don't really interoperate well between browser and node land, and modules are also not treated identically.. so it's not a surprise that blob+module has problems. :)

How to build react js with only one chunk

I have a react js project and im actually dont know how to set webpack settings. After i run "npm run build" i get 10 js files names 1.js 2.js 3.js with main.js. I dont know how to bundle them. I searched some questions but couldnt solve it. Its not my first project in react but i didnt try to
build with webpack before. Thanks for helps.
My webpack.prod.js ;
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ResourceManifestPlugin = require('webpack-fivem-manifest');
module.exports = require('./webpack.common')({
mode: 'production',
// In production, we skip all hot-reloading stuff
entry: [path.join(process.cwd(), 'src/app.js')],
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
inject: true,
}),
new ResourceManifestPlugin(),
],
performance: {
assetFilter: assetFilename =>
!/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename),
},
});
My webpack.common.js :
const path = require('path');
const webpack = require('webpack');
module.exports = options => ({
mode: options.mode,
entry: options.entry,
output: {
path: path.resolve(process.cwd(), 'html'),
filename: '[name].js',
},
module: {
rules: [
{
test: /\.jsx?$/, // Transform all .js and .jsx files required somewhere with Babel
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
// Preprocess our own .css files
// This is the place to add your own loaders (e.g. sass/less etc.)
// for a list of loaders, see https://webpack.js.org/loaders/#styling
test: /\.css$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader'],
},
{
// Preprocess 3rd party .css files located in node_modules
test: /\.css$/,
include: /node_modules/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(eot|otf|ttf|woff|woff2)$/,
use: 'file-loader',
},
{
test: /\.svg$/,
use: [
{
loader: 'svg-url-loader',
options: {
// Inline files smaller than 10 kB
limit: 10 * 1024,
noquotes: true,
},
},
],
},
{
test: /\.(jpg|png|gif)$/,
use: [
{
loader: 'url-loader',
options: {
// Inline files smaller than 10 kB
limit: 10 * 1024,
},
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
enabled: false,
// NOTE: mozjpeg is disabled as it causes errors in some Linux environments
// Try enabling it in your environment by switching the config to:
// enabled: true,
// progressive: true,
},
gifsicle: {
interlaced: false,
},
optipng: {
optimizationLevel: 7,
},
pngquant: {
quality: '65-90',
speed: 4,
},
},
},
],
},
{
test: /\.html$/,
use: 'html-loader',
},
{
test: /\.(mp4|webm)$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
},
},
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: `ifdef-loader`,
options: {
DEBUG: options.mode !== 'production',
version: 3,
'ifdef-verbose': true, // add this for verbose output
'ifdef-triple-slash': true, // add this to use double slash comment instead of default triple slash
},
},
],
},
],
},
plugins: options.plugins.concat([
// Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
// inside your code for any environment checks; Terser will automatically
// drop any unreachable code.
new webpack.EnvironmentPlugin({
NODE_ENV: 'development',
}),
]),
resolve: {
modules: ['src', 'node_modules'],
extensions: ['.js', '.jsx', '.react.js'],
},
});

Unexpected character '#' You may need an appropriate loader to handle this file type

This is what I get when I try to run webpack: the error I get is:
"ERROR in ./v3/app/styles/main.scss
Module parse failed: /Users/vovina/widget-login-react/v3/app/styles/main.scss Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type."
it can't resolve #import, any ideas on this?
my webpack config is as follow:
const childProcess = require('child_process')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const trimEnd = require('lodash/trimEnd')
const webpack = require('webpack')
const path = require('path')
const ENV = {
NODE_ENV: process.env.NODE_ENV,
API: 'https://accounts' + (process.env.NODE_ENV === 'prd' ? '' : '-'
+ process.env.NODE_ENV),
BUILD_VERSION: trimEnd(childProcess.execSync('git rev-list HEAD --
count').toString(), '\n'),
BUILD_DATE: trimEnd(childProcess.execSync('git log --format="%cd" -n
1').toString(), '\n'),
BUILD_COMMIT_ID: trimEnd(childProcess.execSync('git log --format="%h"
-n 1').toString(), '\n')
}
const prodLikeEnvironment = process.env.NODE_ENV === 'stg' ||
process.env.NODE_ENV === 'prd'
const CSS_MAPS = !prodLikeEnvironment
module.exports = {
entry: {
init: [
'./app/init.js'
],
login: [
'./app/login.js'
],
authentication: [
'./v3/app/authenticator.js'
],
common: [
'./app/common.js'
]
},
target: 'web',
output: {
path: path.join(__dirname, 'dist', process.env.NODE_ENV),
pathinfo: true,
publicPath: '/assets/widgets/login/v2/',
filename: '[name].bundle.js',
chunkFilename: '[id].bundle.js',
libraryTarget: 'umd'
},
resolve: {
alias: {
'react': 'preact-compat',
'react-dom': 'preact-compat'
},
modules: [
path.resolve('./app'),
path.resolve('./node_modules')
]
},
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: [/bower_components/, /node_modules/]
},
{
// Transform our own .(scss|css) files with PostCSS and CSS-modules
test: /\.(scss|css)$/,
include: [path.resolve(__dirname, 'v3/app')],
options: {
sourceMap: true
},
loader: [
`style-loader?singleton`,
`css-loader?modules&importLoaders=1&localIdentName=
[local]${process.env.CSS_MODULES_IDENT ||
'_[hash:base64:5]'}&sourceMap=${CSS_MAPS}`,
'postcss-loader',
`sass-loader?sourceMap=${CSS_MAPS}`
].join('!')
},
{
test: /\.(scss|css)$/,
exclude: [path.resolve(__dirname, 'v3/app')],
options: {
sourceMap: true
},
loader: [
`style-loader?singleton`,
`css-loader?sourceMap=${CSS_MAPS}`,
`postcss-loader`,
`sass-loader?sourceMap=${CSS_MAPS}`
].join('!')
},
{
test: /\.(svg|eot|woff|woff2?|ttf|otf)$/,
use: 'base64-font-loader'
},
{
test: /.json$/,
loader: 'json'
},
{
test: /\.jpe?g$|\.gif$|\.png$/,
use: 'base64-image-loader'
},
{
test: /\.html?$/,
loader: 'html'
},
{
test: /\.js$/,
loader: 'strip-loader?strip[]=debug,strip[]=console.log,strip[]=console.debug,strip[]=console.info'
}
]
},
plugins: [
new webpack.LoaderOptionsPlugin({
minimize: true
// postcss: [
// autoprefixer({ browsers: 'last 2 versions' })
// ]
}),
new CopyWebpackPlugin([
{ from: 'public' }
]),
new ExtractTextPlugin('[name].bundle.css'),
new webpack.DefinePlugin({
ENV: JSON.stringify(ENV),
// Only used for react prod bundle. Refer to ENV.NODE_ENV for business
logic
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
output: {
comments: false
},
compress: {
unsafe_comps: true,
properties: true,
keep_fargs: false,
pure_getters: true,
collapse_vars: true,
unsafe: true,
warnings: false,
screw_ie8: true,
sequences: true,
dead_code: true,
drop_debugger: true,
comparisons: true,
conditionals: true,
evaluate: true,
booleans: true,
loops: true,
unused: true,
hoist_funs: true,
if_return: true,
join_vars: true,
cascade: true,
drop_console: true
}
})
]
}
You are using the (scss|css) twice in your configuration file.
Remove that and use the code posted blow:
Before using, you must first npm install raw-loader.
I think you've already installed the sass-loader.
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw-loader'
},
// // css global which not include in components
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
use: ExtractTextPlugin.extract({
use: 'raw-loader'
})
},
{
test: /\.scss$/,
include: helpers.root('src', 'app'),
use: ['raw-loader', 'sass-loader']
},
// // SASS global which not include in components
{
test: /\.scss$/,
exclude: helpers.root('src', 'app'),
use: ExtractTextPlugin.extract({
use: ['raw-loader', 'sass-loader']
})
}
Add my root()function.
var path = require('path');
var _root = path.resolve(__dirname, '..');
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [_root].concat(args));
}
exports.root = root;
Hope this will work.

Lazy Loading not work in WebPack Angular 2 project

I'm new to webPack and I have a problem with my project in Angular 2.
I'm trying to apply Lazy Loading on the modules, but I have always the same mistake for hours.
The error occurs when i need to load a child module. (During the rooting)
export const routes: Routes =
[
{ path: '', redirectTo: '/account', pathMatch: 'full' },
{ path: 'account', component: LoginComponent },
{ path: 'student', canLoad: [AuthGuard], loadChildren: './student.module/app.student.module#AppStudentModule' },
{ path: 'teacher', canLoad: [AuthGuard], loadChildren: './teacher.module/app.teacher.module#AppTeacherModule' },
{ path: 'administrative', canLoad: [AuthGuard], loadChildren: './secretary.module/app.secretary.module#AppSecretaryModule' },
{ path: 'unauthorized', component: PageUnauthorized },
{ path: 'terms', component: TermsComponent},
{ path: '**', component: PageNotFound }
];
I show you my current configuration:
My webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OptimizeJsPlugin = require('optimize-js-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
const root = path.join.bind(path, path.resolve(__dirname));
// Webpack Config
const webpackConfig = {
entry: {
app: './src/main.ts',
polyfills: './src/polyfills.ts',
vendor: './src/vendor.ts'
},
output: {
publicPath: '/public/js',
path: path.resolve(__dirname, './public/js')
},
plugins: [
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
root('./src'), // location of your src
{} // a map of your routes
),
new webpack.ProvidePlugin({
'lodash': 'lodash',
'moment': 'moment',
'moment-timezone': 'moment-timezone',
'angular2-mdl': 'angular2-mdl',
'jquery': 'jquery'
}),
new CopyWebpackPlugin([ { from: 'src/assets/i18n', to: '/assets/i18n' } ]),
new ExtractTextPlugin('../css/styles.css')
],
module: {
loaders: [
{
test: /\.ts$/,
loaders: [
'awesome-typescript-loader',
'angular2-router-loader',
'angular2-template-loader'
]
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader?minimize=true'
}),
include: [root('assets', 'css'), /node_modules/]
},
{
test: /\.scss$/,
loader: 'raw-loader!sass-loader'
},
{test: /\.html$/, loader: 'raw-loader'},
{ test: /\.(png|jpg|woff|woff2|eot|ttf|TTF|svg)$/, loader: 'url-loader?limit=100000' }
]
}
};
const defaultConfig = {
devtool: 'source-map',
output: {
filename: '[name].js',
sourceMapFilename: '[name].map',
chunkFilename: '[name]-chunk.js'
},
resolve: {
extensions: [ '.ts', '.js' ],
modules: [ path.resolve(__dirname, 'node_modules') ]
},
node: {
global: true,
crypto: 'empty',
__dirname: true,
__filename: true,
process: true,
Buffer: false,
clearImmediate: false,
setImmediate: false
}
};
const commonConfig = webpackMerge(defaultConfig, webpackConfig);
const prodConfig = {
devtool: 'source-map',
plugins: [
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
sequences : true, // join consecutive statemets with the “comma operator”
properties : true, // optimize property access: a["foo"] → a.foo
dead_code : true, // discard unreachable code
drop_debugger : true, // discard “debugger” statements
unsafe : false, // some unsafe optimizations (see below)
conditionals : true, // optimize if-s and conditional expressions
comparisons : true, // optimize comparisons
evaluate : true, // evaluate constant expressions
booleans : true, // optimize boolean expressions
loops : true, // optimize loops
unused : true, // drop unused variables/functions
hoist_funs : true, // hoist function declarations
hoist_vars : false, // hoist variable declarations
if_return : true, // optimize if-s followed by return/continue
join_vars : true, // join var declarations
cascade : true, // try to cascade `right` into `left` in sequences
side_effects : true, // drop side-effect-free statements
warnings : true, // warn about potentially dangerous optimizations/code
},
output: {
comments: false,
space_colon: false
}
}),
new OptimizeJsPlugin({
sourceMap: false
}),
new webpack.optimize.OccurrenceOrderPlugin()
]
};
const testConfig = {
devtool: 'inline-source-map',
module: {
rules: [
{test: /\.scss$/, loaders: ['raw-loader', 'postcss-loader', 'sass-loader'], exclude: [/\.global\.scss$/, /node_modules/]},
{test: /\.global\.scss$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'], exclude: [/node_modules/]},
{test: /\.css$/, loaders: ['style-loader', 'css-loader'], include: [/node_modules/]},
{test: /\.css$/, loaders: ['to-string-loader', 'css-loader'], exclude: [/node_modules/]},
{test: /\.html$/, loader: 'raw-loader'},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff',
name: '../fonts/[name].[ext]',
publicPath: '/fonts/'
}
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
options: {
name: '../fonts/[name].[ext]',
publicPath: '/fonts/'
}
},
{
test: /\.ts$/,
use: [
{
loader: 'awesome-typescript-loader',
query: {
// use inline sourcemaps for "karma-remap-coverage" reporter
sourceMap: false,
inlineSourceMap: true,
compilerOptions: {
// Remove TypeScript helpers to be injected
// below by DefinePlugin
removeComments: true
}
},
},
'angular2-template-loader'
],
exclude: [/\.e2e\.ts$/]
},
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader',
exclude: [/spec-bundle\.js/, /node_modules/]
},
{
enforce: 'post',
test: /\.(js|ts)$/,
loader: 'istanbul-instrumenter-loader',
exclude: [
/spec-bundle\.js/,
/\.(e2e|spec)\.ts$/,
/node_modules/
]
}
]
}
};
const devConfig = {
devtool: 'cheap-module-source-map',
module: {
loaders: [
{
test: /\.ts$/,
loader: 'tslint-loader',
options: {
configFile: 'tslint.json'
},
exclude: [/\.(spec|e2e)\.ts$/, /node_modules/]
},
]
}
};
switch (process.env.NODE_ENV) {
case 'staging':
case 'production':
module.exports = webpackMerge(commonConfig, prodConfig);
break;
case 'test':
module.exports = webpackMerge(commonConfig, testConfig);
break;
case 'development':
default:
module.exports = webpackMerge(commonConfig, devConfig);
}
And this is my tsconfig.json:
{
"angularCompilerOptions": {
"entryModule": "src/app.module#AppModule",
"genDir": "./ngfactory",
"debug": false
},
"awesomeTypescriptLoaderOptions": {
"useWebpackText": true
},
"buildOnSave": false,
"compileOnSave": false,
"compilerOptions": {
"allowUnusedLabels": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [
"es6",
"dom"
],
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": false,
"noImplicitReturns": true,
"outDir": "public/js",
"rootDir": ".",
"sourceMap": true,
"suppressImplicitAnyIndexErrors": true,
"target": "ES5",
"typeRoots": [
"node_modules/#types"
],
"types": ["node", "jasmine"]
},
"exclude": [
"node_modules",
"public"
]
}
And so i have this error:
Please help me!!
Thanks

Webpack2 + Typescript2 fails to dynamic import json

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.

Categories

Resources