Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack, restrict what can be imported

Is there a way in webpack to restrict what files can be imported?

Say I want to be able to import files that are in the same directory, as well as the parent directory, but nothing above that parent directory? For example:

These work

import { blah } from "./script.js";

import { blah2 } from "./../gui/textbox.js";

import { blah3 } from  "./../I/can/go/as/deep/down/as/I/want/here.js";

But this wouldn't work

import { passwords } from "./../../passwords.txt";

Because that would go up two (or x number of) directories, instead of just one.

like image 480
Isaac Avatar asked Mar 20 '19 22:03

Isaac


People also ask

Does webpack support import?

The imports loader allows you to use modules that depend on specific global variables. This is useful for third-party modules that rely on global variables like $ or this being the window object. The imports loader can add the necessary require('whatever') calls, so those modules work with webpack.

What kind of modules can webpack support?

Webpack supports the following module types natively: ECMAScript modules. CommonJS modules. AMD modules.

How does webpack import work?

Webpack is a command line tool to create bundles of assets (code and files). Webpack doesn't run on the server or the browser. Webpack takes all your javascript files and any other assets and transforms then into one huge file. This big file can then be sent by the server to a client's browser.

What is chunking in webpack?

If you don't want all of your code be put into a single huge bundle you will split it into multiple bundles which are called chunks in webpack terminology. In some cases you will define how your code is split chunks yourself (with an entry that points to multiple files and an output file template like [name].


1 Answers

react-dev-utils has a plugin for this.

This Webpack plugin ensures that relative imports from app's source directories don't reach outside of it.

var path = require('path');
var ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');

module.exports = {
  // ...
  resolve: {
    // ...
    plugins: [
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
      // ...
    ],
    // ...
  },
  // ...
};
like image 172
UjinT34 Avatar answered Oct 12 '22 06:10

UjinT34