Currently in the process of setting up webpack with Typescript for my project using resources from the official tutorial. Below is an overview of my folder structure and key files:
├── dist
│ ├── bundle.js
│ └── index.html
├── package-lock.json
├── package.json
├── src
│ └── index.ts
├── tsconfig.json
└── webpack.config.js
src/index.ts
:
// import _ from 'lodash';
const result = _.add(5, 6);
console.log(result);
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'),
},
};
tsconfig.json
:
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"strict": true,
"module": "es6",
"target": "es5",
"allowSyntheticDefaultImports": true
}
}
One observation made in index.ts
is that the lodash import is commented out after running npm i lodash @types/lodash
. Surprisingly, there isn't a TypeScript error flagged, as depicted below:
https://i.sstatic.net/EPPfA.png
Moreover, compiling the project into a bundle using npx webpack
(tsc src/index.ts
also works). However, upon browser inspection, the following console message appears:
https://i.sstatic.net/zplsR.png
Evidently, TypeScript wrongly assumes that _
is globally defined (unknown how), despite the absence of an actual import. Uncommenting the import resolves the ReferenceError, yet it remains unclear why the TypeScript Compiler fails to catch this issue.
An interesting discovery was switching the file content to the following, triggering a warning with red squiggly lines under _.add
:
// import _ from 'lodash';
import a from 'lodash';
const result = _.add(5, 6);
console.log(result);
'_' refers to a UMD global, but the current file is a module. Consider adding an import instead. ts(2686)