Import node_modules from non relative location

Viewed 37

I'm trying to import a custom made framework that I have pushed to npmjs.org. Im building a .js file and a .d.ts file.

When actually importing I get no errors until I compile. All the map links work and point to the source when ctrl+clicking on them etc and the types file seems to be picked up.

What happens when I compile is any file importing any of these modules tries to import it relative to its own path. I have gone through a bunch of question on stack already and tried many of the suggestions. I have tried using paths in the tsconfig which doesnt seem to work.

Error:

ERROR in ./src/scripts/game/mGameModel.ts 17:16-34

Module not found: Error: Can't resolve 'Scratch' in '/Users/derek/Projects/ghg/cash-mania/src/scripts/game'

The actual library files are located at;

node_modules/@myorg/game-framework/dist/Scratch.js node_modules/@myorg/game-framework/dist/Scratch.d.ts node_modules/@myorg/game-framework/dist/Scratch.js.map

Am I building the types file incorrectly maybe or what could I possibly be doing wrong.

Here is my tsconfig

{
  "compilerOptions": {
    "target": "ES5",
    "module": "commonjs",
    "strict": true,
    "noImplicitAny": false,
    "esModuleInterop": true,
    "allowUnreachableCode": false,
    "experimentalDecorators": true,
    "sourceMap": true,
    "strictPropertyInitialization": false,
    "typeRoots": [
      "./node_modules/phaser/types",
      "./node_modules/@myorg/game-framework/dist/",

    ],
    "baseUrl": "./",
    "types": [
      "node",
      "phaser",
    ],
    "paths": {
      "Scratch": [
        "./node_modules/@myorg/game-framework/dist/Scratch"
      ]
    },
    "lib": ["dom", "es5", "esnext"]
  },
  "include": [
    "node_modules/phaser3-rex-plugins-types",
    "node_modules/@myorg/game-framework/dist",
  ],
}

So I have tried adding the paths, and Ive tried that multiple ways using Scratch/ and Scratch/* as I saw in other answers for similar questions.

I also tried adding the folder into the include and made sure to set baseUrl to ./ but no matter what I do it always seems to try to import my Scratch Module from the directory of the file importing it.

Here is my webpack file

const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const PACKAGE = require('./../package.json');
const version = PACKAGE.version;
const name = PACKAGE.name;

module.exports = {
  entry: ['./src/scripts/Index.ts'],
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].bundle.js',
    chunkFilename: '[name].chunk.js'
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
    modules: ["node_modules", 'src']
  },
  module: {
    rules: [
      { 
        test: /\.tsx?$/, 
        include: path.join(__dirname, '../src'), 
        loader: 'ts-loader'
      },
      { 
        test: /\.ts$/,
        loader: 'string-replace-loader',
        options: {
          search: '${WEBPACK_VERSION}',
          replace: version,
        }
      }
    ]
    
    
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
          filename: '[name].bundle.js'
        }
      }
    }
  },
  plugins: [
    new HtmlWebpackPlugin({ gameName: name, template: 'src/index.html' }),
    new CopyWebpackPlugin({
      patterns: [
        { from: 'src/assets', to: 'assets' },
      ],
    })
  ]
}
1 Answers

it may not be exactly what you are looking for but here is how I use path import with '@'

1 - install these babel dependencies, it will help you compile the paths:

npm install -D @babel/cli @babel/node @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators @babel/preset-env @babel/preset-typescript babel-plugin-module-resolver babel-plugin-transform-typescript-metadata

2 - create a file called babel.config.js, in it you will create custom paths...

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: '14.19.13'  // NODE VERSION COMPILE
        }
      }
    ],
    '@babel/preset-typescript'
  ],
  plugins: [
    ['module-resolver', {
      alias: {
        '@domain': './src/domain',  // HERE <<<<<<< 
      }
    }],
    'babel-plugin-transform-typescript-metadata',
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-proposal-class-properties', { loose: true }]
  ],
  ignore: [
    '**/*.spec.ts',
    '**/*.test.ts',
    'test/**/*.spec.ts'
  ]
}

3 - in your ts.config.json, in the parameter "path" seven also how you want to import...

"paths":{
    "@main/*": ["main/*"],
}

4 - in your script create one for build like this...

  "scripts": {
    "build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored"
}

here is a project of mine in case you want to base yourself on it: https://github.com/Christiangsn/Nodejs-API-IntegrationWithFacebook/blob/Master/package.json

bonus: if you want an alternative to nodemon use: https://www.npmjs.com/package/tsconfig-paths

Related