How to import an external file from project root w

2020-04-21 05:33发布

问题:

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?

回答1:

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.