webpacker: [ts] Property `context` does not exist on type 'NodeRequire'
Hi there!
Thanks for all your hard work on webpacker, it’s excellent! I’m having a bit of an issue using typescript and stimulus on Rails 5.1 and webpacker 3.2.2.
I installed webpacker, typescript and stimulus using the following:
bundle exec rails webpacker:install
bin/rails webpacker:install:typescript
bin/rails webpacker:install:stimulus
Create a file called application.ts:
import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"
const application = Application.start()
const context = require.context("controllers", true, /.ts$/)
application.load(definitionsFromContext(context))
I get a compiler error at
const context = require.context("controllers", true, /.ts$/) // [ts] Property 'context' does not exist on type 'NodeRequire'.
My tsconfig.json:
{
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es6", "dom"],
"module": "es6",
"moduleResolution": "node",
"sourceMap": true,
"target": "es5",
"types": [
"webpack",
"webpack-env"
]
},
"exclude": [
"**/*.spec.ts",
"node_modules",
"vendor",
"public"
],
"compileOnSave": false
}
My package.json
{
"name": "canopy",
"private": true,
"dependencies": {
"@rails/webpacker": "^3.2.2",
"stimulus": "^1.0.1",
"ts-loader": "^3.5.0",
"typescript": "^2.7.2"
},
"version": "1.0.0",
"repository": "git@github.com:sunnyrjuneja/canopy.git",
"author": "Sunny Juneja <jr.sunny@gmail.com>",
"devDependencies": {
"@types/webpack": "^3.8.8",
"@types/webpack-env": "^1.13.5",
"webpack-dev-server": "^2.11.1"
}
}
My understanding is the types: […] in tsconfig would solve this problem. It’s why reaching out here.
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 2
- Comments: 15 (4 by maintainers)
Commits related to this issue
- Install @types/webpack-env Stimulus + TypeScript cause this error: https://github.com/rails/webpacker/issues/1276 — committed to annict/annict by shimbaco 5 years ago
I think reinstalling
types/webpack-env
is enough or installing it if missing.Command:
npm i -D @types/webpack-env
{ “compilerOptions”: { “types”: [ “node”, “webpack-env” ] } }
As said by @Legends installing webpack typings extends the require with the context method so it works:
npm i -D @types/webpack-env
an easy but ugly workaround:
require['context']
npm i -D @types/webpack-env and then restart
I reread the issue and was able to solve my problem.
[hmm, I thought that was the answer: the red ink is gone from the vscode window; but when I build/compile with ng / tsc, it now complains: 'Cannot find name ‘require’. (and yes, @types/node is installed)]
Ah! it’s an Angular build, so put the “types”: [“node”, “webpack-env”] in tsconfig.app.json (even though it “extends”: tsconfig.json)
Yes, sometimes it’s really weird…