skip to Main Content

By using export keyword, we can export anything from a file to another file in JavaScript. But is their any way to export for specific files. So that other file can’t import from this file.

export const t = {
a:'this will export for index.js only'
}

2

Answers


  1. If you are referring to how java controls access of classes to the rest of the application public, private, protected then no. If you only want a singular file to be able to use a variable then declare the variable in the file you want to use. or look into changing the architecture of your application. Ex: change your function to use dependency injection.

    Login or Signup to reply.
  2. There’s no way to achieve that directly, since import.meta does not contain that information. But you can do it if you export a factory function instead, that way you can access the caller file by using Error.stack.

    module.js

    const callerUrl = () => {
      const error = new Error()
      const lines = error.stack?.split('n')
      let line = lines && lines[3] || ''
      line = line.replace('at', '')
      line = line.replace(/:[0-9]+:[0-9]+/, '')
      return line.trim()
    }
    
    export default () => {
      const file = callerUrl();
      const x = {};
    
      if(file.endsWith('/index.js')) {
        x.a = 'from index.js'
      }
      else if(file.endsWith('/foo.js')) {
        x.a = 'from foo.js'
      }
    
      return x;
    }
    

    index.js

    import factory from './module.js';
    import './foo.js';
    
    console.log(factory());
    // { a: "from index.js" }
    

    See: Access the calling file name from within a function in a different file


    I don’t recommend exporting something based on the caller file though.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search