Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...