Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import an external file from project root with webpack?

I am building an npm package that will take in custom rules from the project root - similar to the way prettier looks for a .prettierrc in the project root.

In my package I am using webpack to compile the build. My app uses react, which I am pulling in externally so that the package is retrieved at runtime instead of being bundled at build time.

webpack.config.js

    module.exports = {
  entry: "./src/index.js",
  output: {...},
  module: {...},
  resolve: {
    modules: [path.resolve("./src"), path.resolve("./node_modules")],
    alias: {
      react: path.resolve(__dirname, "./node_modules/react"),
      "react-dom": path.resolve(__dirname, "./node_modules/react-dom")
    }
  },
  externals: {
    react: {
      commonjs: "react",
      commonjs2: "react",
      amd: "React",
      root: "React"
    },

    "react-dom": {
      commonjs: "react-dom",
      commonjs2: "react-dom",
      amd: "ReactDOM",
      root: "ReactDOM"
    }
  }
};

Here in the externals you can see that I am excluding react and react-dom from the build.

Now, I need a way to import a regular settings.js file from the project root, rather than importing a library from the node_modules. Does webpack have this capability?

So far I have tried using externals to import it like so:

externals: {
    react: {...},
    "react-dom": {...},
    "settings": { commonjs: "settings.js" }
  }

I know this is wrong, but is there something similar that I can do in order to import an external .js file at runtime from the project directory?

like image 614
Truitt7 Avatar asked Jan 18 '19 15:01

Truitt7


1 Answers

I would encourage you to bundle instead of trying to import things at runtime. Webpack is a bundler. Things get messy when you try to work around what its designed to do.

And yes, you can import files outside of the root directory into your bundle. Here is an example from one of my apps that uses external code.

{
    test: /\.js?$/,
    include: [
      path.resolve(__dirname),
      path.resolve(__dirname, "../Public/js/src/common")
    ],
    exclude: /node_modules/,
    loader: "babel-loader"
  }

I also create an alias.

      common: path.resolve(__dirname, "../Public/js/src/common"),

Webpack will bundle this file with your app when you import it.

like image 77
Chase Avatar answered Sep 28 '22 14:09

Chase