[javascript] How do I include a JavaScript file in another JavaScript file?

You can also use gulp, gulp-concat, gulp-typescript with /// <reference path= includes:

packages.json

{
  "scripts": {
    "gulp": "gulp main"
  },
  "dependencies": {
    "@types/gulp": "^4.0.6",
    "@types/gulp-concat",
    "@types/gulp-typescript",
    "gulp": "^4.0.2",
    "gulp-concat": "^2.6.1",
    "gulp-resolve-dependencies": "^3.0.1",
    "gulp-typescript": "^6.0.0-alpha.1",
    "typescript": "^3.7.3"
  }
}

src/someimport.ts

class SomeClass {
    delay: number;
}

src/main.ts

/// <reference path="./someimport.ts" />

someclass = new SomeClass();
someclass.delay = 1;

This main gulp task (on gulpfile.js) targets only the src/main.js file, resolving all its /// <reference path=... include references. These includes are know as Triple-Slash Directives and they are used only for transpilers tools to combine files. In our case, they are used explicitly by .pipe(resolveDependencies({ and by typescript itself when checking the file for missing types, variables, etc.

  1. https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html
  2. When do I need a triple slash reference?

Refer to https://github.com/ivogabe/gulp-typescript#api-overview if you would like to customize the var tsProject = ts.createProject call and not use a tsconfig.json file or override its parameters.

gulpfile.js

var gulp = require("gulp");
var concat = require('gulp-concat');
var resolveDependencies = require('gulp-resolve-dependencies');

var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");

gulp.task("main", function() {
  return gulp
    .src(["src/main.ts"])
    .pipe(resolveDependencies({
      pattern: /^\s*\/\/\/\s*<\s*reference\s*path\s*=\s*(?:"|')([^'"\n]+)/gm
    }))
    .on('error', function(err) {
        console.log(err.message);
    })
    .pipe(tsProject())
    .pipe(concat('main.js'))
    .pipe(gulp.dest("build/"));
});

If you wold like to target all your type script project files instead of only src/main.ts, you can replace this:

  return gulp
    .src(["src/main.ts"])
    .pipe(resolveDependencies({
    ...
// -->
  return tsProject
    .src()
    .pipe(resolveDependencies({
    ...

If you do not want to use typescript, you can use this simplified gulpfile.js and remove all typescript includes from package.json:

gulpfile.js

var gulp = require("gulp");
var concat = require('gulp-concat');
var resolveDependencies = require('gulp-resolve-dependencies');

gulp.task("main", function() {
  return gulp
    .src(["src/main.js"])
    .pipe(resolveDependencies({
      pattern: /^\s*\/\/\/\s*<\s*reference\s*path\s*=\s*(?:"|')([^'"\n]+)/gm
    }))
    .on('error', function(err) {
        console.log(err.message);
    })
    .pipe(concat('main.js'))
    .pipe(gulp.dest("build/"));
});

packages.json

{
  "scripts": {
    "gulp": "gulp main"
  },
  "dependencies": {
    "gulp": "^4.0.2",
    "gulp-concat": "^2.6.1",
    "gulp-resolve-dependencies": "^3.0.1"
  }
}

Then, after running the command npm run gulp, the file build/main.js is created with the following as its contents:

build/main.js

class SomeClass {
}
/// <reference path="./someimport.ts" />
someclass = new SomeClass();
someclass.delay = 1;

Which allows me to include it in the browser with the script tag, after serving the build directory files:

<html>
    <head>
        <script src="main.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            console.log(someclass.delay);
        </script>
    </body>
</html>

Related questions:

  1. https://www.typescriptlang.org/docs/handbook/gulp.html
  2. Can I use the typescript without requireJS?
  3. Gulp simple concatenation of main file that requires another JS file
  4. Client on node: Uncaught ReferenceError: require is not defined
  5. How can typescript browser node modules be compiled with gulp?
  6. Concatenate files using babel
  7. How to require CommonJS modules in the browser?
  8. Is there an alternative to Browserify?

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to import

Import functions from another js file. Javascript The difference between "require(x)" and "import x" pytest cannot import module while python can How to import an Excel file into SQL Server? When should I use curly braces for ES6 import? How to import a JSON file in ECMAScript 6? Python: Importing urllib.quote importing external ".txt" file in python beyond top level package error in relative import Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Examples related to include

"Multiple definition", "first defined here" errors Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 Include PHP file into HTML file Cannot open include file with Visual Studio How to make Apache serve index.php instead of index.html? Include php files when they are in different folders Already defined in .obj - no double inclusions What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files? What is the correct syntax of ng-include? Visual Studio can't 'see' my included header files