【问题标题】:Load shared assets between multiple entries in Webpack在 Webpack 中的多个条目之间加载共享资产
【发布时间】:2020-02-16 13:51:08
【问题描述】:

我正在开发一个基于 Node.js、Express 和 Webpack 的应用程序。

应用程序有多个页面(具有不同的客户端逻辑),所以我使用的是自定义结构文件夹,没有唯一的 /src 文件夹。

这是结构:

|── clients
    └── client_1
        └── client_1_logic.js
        └── client_1_style.css
    └── client_2
        └── client_2_logic.js
        └── client_2_style.css

|── server
    └── index.js (node.js server entry point)
    └── other_serverside_stuff.js

|── public (public static folder)
    └── static_files (audio, img...)
    └── js (webpack bundled scripts)
        └── client_1.bundle.js
        └── client_2.bundle.js

|── shared (here's the question)

我对当前的结构很满意,因为我可以以一种简洁的方式分离逻辑,仅在需要时导入模块,捆绑所有内容并将其放在公共文件夹中,这样我就可以从客户端检索文件运行时-边。 公用文件夹设置为静态文件夹,express:app.use(express.static(path.join(__dirname, '../public')));

我想要做的是将一些文件放在shared 文件夹中(例如一个普通的配置文件,或者一个基本的.css 模板),然后在客户端逻辑中导入它们。 例如,假设shared文件夹中有一个config.js,我想将它导入client_1_logic.js这样的方式:

// libs
import {html, render} from 'lit-html';
// style
import 'bootstrap/dist/css/bootstrap.min.css';
// config
import config from './shared/config.js';

// do something with imported modules ...

现在我收到错误 Module not found: Error: Can't resolve './shared/config.js'

如果我将shared 文件夹放在client_1client_2 子文件夹中,它会起作用,但我真的不想复制所有文件。

这是我的webpack.config.js

const path = require('path');

module.exports = {
  mode: 'development',
  entry: {
    player: './clients/client_1/client_1_logic.js',
    controller: './clients/client_2/client_2_logic.js'
  },
  devtool: 'inline-source-map',
  output: {
    filename: '[name].bundle.js',
    path: path.join(__dirname, 'public/js/'),
    publicPath: '/',
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      }
    ]
  }
};

提前非常感谢, 弗朗切斯科

【问题讨论】:

    标签: javascript node.js express webpack


    【解决方案1】:

    好的,我找到了一个干净的解决方案:

    以这种方式将解析规则添加到webpack.config.js

    resolve: {
      alias: {
        config: path.join(__dirname, 'shared/'),
      }
    }
    

    我可以通过这种方式从客户端导入文件:

    import config from 'shared/config.js'(没有./

    我们开始吧!

    【讨论】:

      猜你喜欢
      • 2012-07-22
      • 2021-07-13
      • 2023-03-27
      • 2015-10-16
      • 2021-09-04
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      相关资源
      最近更新 更多